teuneboon
teuneboon

Reputation: 4064

Mysqli prepared statement num_rows with multiple parameters

I have the following script:

<?php
$mysqli = new mysqli('localhost', 'user', 'password', 'database');

$statement = $mysqli->stmt_init();

$query = 'SELECT * FROM table WHERE id = ? AND active = 1';
$statement->prepare($query);
$parameters = array('i');
$inputParameters = array(10);
foreach ($inputParameters as $param) {
    $parameters[] =& $param;
}
call_user_func_array(array($statement, 'bind_param'), $parameters);
$statement->execute();
$statement->store_result();
echo $statement->num_rows;
?>

Which returns exactly the right number of rows.

But when I change the script to:

<?php
$mysqli = new mysqli('localhost', 'user', 'password', 'database');

$statement = $mysqli->stmt_init();

$query = 'SELECT * FROM table WHERE id = ? AND active = ?';
$statement->prepare($query);
$parameters = array('ii');
$inputParameters = array(10, 1);
foreach ($inputParameters as $param) {
    $parameters[] =& $param;
}
call_user_func_array(array($statement, 'bind_param'), $parameters);
$statement->execute();
$statement->store_result();
echo $statement->num_rows;
?>

It returns 0. Does anyone have an explanation for that? To me it looks like num_rows stops working as soon as you have more than 1 param bound to the statement.

p.s: in the full script there's a reason to use call_user_func_array here, not using call_user_func_array gives the same result.

Upvotes: 0

Views: 1607

Answers (1)

teuneboon
teuneboon

Reputation: 4064

I found the answer after a lot of debugging: $parameters will be array('ii', 1, 1) in the second code. This is because of the reference used there. Changing foreach ($inputParameters as $param) { to foreach ($inputParameters as &$param) { fixed the problem

Upvotes: 1

Related Questions