bind_param() dynamic

Asked

Viewed 636 times

1

I have the following class:

class BindParam{
    private $values = array(), $types = '';

    public function add( $type, &$value ){
        $this->values[] = $value;
        $this->types .= $type;
    }

    public function get(){
        return array_merge(array($this->types), $this->values);
    }
} 

and this is my code to generate sql:

if(!empty($dataIni)){
    $qArray[] = "BETWEEN V.DATA_EMISSAO ?";
    $bindParam->add('s', $dataIni);
}
if(!empty($dataFim)){
    $qArray[] = "?";
    $bindParam->add('s', $dataFim);
}
$queryNFe .= implode(' AND ', $qArray);
$param = $bindParam->get();
$sqlNFe = $mysqli->prepare($queryNFe);
call_user_func_array(array($sqlNFe, 'bind_param'), $param);
$sqlNFe->execute();

The query clause is mounting right, the error is in call_user_func_array()

Warning: call_user_func_array() expects Parameter 1 to be a Valid callback, first array Member is not a Valid class name or Object in

I know it’s the first parameter but I can’t see what’s wrong

I changed the code:

if(!empty($dataIni)){
    $qArray[] = "V.DATA_EMISSAO BETWEEN ?";
    $bindParam->add('s', $dataIni);
}
if(!empty($dataFim)){
    $qArray[] = "?";
    $bindParam->add('s', $dataFim);
}
$queryNFe .= implode(' AND ', $qArray);
$param = $bindParam->get();
$sqlNFe = $mysqli->prepare($queryNFe) or die($mysqli->error);
call_user_func_array(array($sqlNFe, 'bind_param'), $bindParam->get());
//$sqlNFe->bind_param('ss', $dataIni, $dataFim); 
$sqlNFe->execute();

But now the mistake is this:

Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a Reference, value Given in

  • When you pass, manually the values to bind_param right or some mistake appears?

  • if you go like this: $sqlNfe->bind_param('ss', $dataInicio, $dataFim) works fine

  • See if this returns another error, $mysqli->prepare($queryNFe) or die($mysqli->error);

  • no error @rray.

  • 2

    Now the error is simpler, you need to pass the array by reference and not as method return ... once solved so foreach($values as $valores){ $ref[] = &$valores;} ... maybe there’s something better.

  • Thank you all, I’ve already put the solution using a foreach() @rray

Show 1 more comment

1 answer

1


I decided here with this function:

function refValues($arr){
    if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
    {
        $refs = array();
        foreach($arr as $key => $value)
            $refs[$key] = &$arr[$key];
        return $refs;
    }
    return $arr;
}

so I just changed:

call_user_func_array(array($sqlNFe, 'bind_param'), refValues($param));

Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.