Search code examples
phpcall-user-func-array

call_user_func_array "doesn't work" with bind_param when passing array already in variable


i'm having trouble using call_user_func_array in this code

$stmt=$mysqli->prepare($query);
$txt=array('ii',1,1);
call_user_func_array(array($stmt,"bind_param"),$txt);
$stmt->execute();
$result=$stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC)){
    $r[$count]=$row;
    $count++;
}

Using the $txt variable gives an error with fetch_array():

Call to a member function fetch_array() on boolean

But, if i create the array in the code it works fine. Example:

...
call_user_func_array(array($stmt,"bind_param"),array('ii',1,1));
...

Solution

  • If course it would be nice to know what kind of a query is involved, but in any event the following code works:

    <?php
    error_reporting(E_ALL);
    $id=5;
    $code = 'GR';
    $country='Greece';
    
    $mysqli = new mysqli("localhost", "root", "", "exp");
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . 
    
    $mysqli->connect_error;
    }
    echo $mysqli->host_info . "\n";
    
    if (!($stmt = $mysqli->prepare("INSERT INTO countries VALUES (?,?,?)"))) {
        echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
    }
    
    //$stmt->bind_param('iss', $id, $code, $country);
    
    $params = array('iss',$id,$code,$country);
    $tmp = array();
    foreach($params as $key => $value) $tmp[$key] = &$params[$key];
    
    call_user_func_array( array($stmt, 'bind_param'), $tmp);
    
    
    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
    

    The code only works with my software when the $params array includes the letters specifying the type of data. Also the params themselves need to be references and not values. Note: I did borrow the code to turn values into references from this member of Stackoverflow.