phpoopmysqliprepared-statementbindparam

Passing array through bind_param


I'm passing an array of values through a bind_param function, the way I do this is like this:

<?php
class Query{
    private $_mysqli;

    /*
     * @param object $mysqli
     */
    public function __construct($mysqli)
    {
        $this->_mysqli = $mysqli;
    }

    /*
     * @param string query
     * @param string $types
     * @param array $values
     */
    public function read($query = "", $type = "", $params = array())
    {
        $query = ($query === "") ? die("Read error: Query") : $query;
        $type = ($type === "") ? die("Read error: Type") : array($type);
        $params = (count($params) == 0) ? die("Read error: Params") : $params;

        $values = array();
        foreach($params as $key => $value) {
            $values[$key] = &$params[$key];
        }

        if ($stmt = $this->_mysqli->prepare($query))
        {
            call_user_func_array(array($stmt, "bind_param"), array_merge($type, $values));
            $stmt->execute();
            $fields = array();
            for($i=0; $i<count($params); $i++){
                $fields[$i] = $params[$i];
            }
            call_user_func_array(array($stmt, "bind_result"), $fields);

            $array = array();
            while($data = $stmt->fetch())
            {
                $array[] = $data;
            }

            return $array;
        }
    }
}

This is the way I use my function

<?php
//$mysqli is the mysqli connection
$query = new Query($mysqli);

$query_str = "SELECT * FROM users WHERE voornaam = ? AND achternaam = ?";
$types = "ss";
$params = array("Firstname", "Lastname");
var_dump($query->read($query_str, $types, $params));
?>

The part where I get stucked is:

<?php
$fields = array();
for($i=0; $i<count($params); $i++){
    $fields[$i] = $params[$i];
}
call_user_func_array(array($stmt, "bind_result"), $fields);

$array = array();
while($data = $stmt->fetch())
{
    $array[] = $data;
}
?>

Im not sure where it goes wrong, I have a feeling at the while loop. hope you guys can help me making this function working :)


Solution

  • you are binding results , so you don't need to assign your fetched data to new variable,

    mysqli_stmt::bind_result -- mysqli_stmt_bind_result — Binds variables to a prepared statement for result storage

    while you are using call_user_func_array , and according to this comment, your loop :

    while($data = $stmt->fetch())
    {
        $array[] = $data;
    }
    

    may be as follows:

    while($stmt->fetch())
    {
        // params which you had bind it into bindParams
        $array[] = $params;
    }