3

I am writing a wrapper class for MySQLi. In there, I am writing a function to accept a query and variable number of parameters where I can invoke mysqli_stmt::bind_param. Here is the code:

<?php
    class DbHelper {
        ....
        public function Execute($query, $params){
            $this->open(); # Opens a connection to the database using MySQLi API
            $stmt = $this->mysqli->prepare($query);
            try{
                $result = call_user_func_array(array($stmt, 'bind_param'), $params);
            }
            catch(Exception $ex){
                # Handle Exception
            }
        }
        ....
    }
?>

Here's how I am calling the function:

<?php
    $db = new DbHelper();
    $params = array('i', $stateID);
    $result = $db->Execute('SELECT * FROM mst_cities WHERE State_ID = ?', $params);    
?>

When I run the code, I get an warning as this:
Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given in......

What should I do?

1 Answer 1

4

From the docs:

Note:

Care must be taken when using mysqli_stmt_bind_param() in conjunction with call_user_func_array(). Note that mysqli_stmt_bind_param() requires parameters to be passed by reference, whereas call_user_func_array() can accept as a parameter a list of variables that can represent references or values.

There are some workarounds in the comments, for example see this:

call_user_func_array(array($stmt, 'bind_param'), refValues($params));

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Another problem. Using $stmt->execute(); $meta = $stmt->result_metadata(); and echoing $meta['num_rows'] returns 0 and echoing $this->mysqli->affected_rows returns -1. Otherwise, the query works fine when used directly. What could be the problem?
@kush.impetus Did you try $stmt->num_rows?
Maybe you should open another question for this particular problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.