Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: "Value Expected To Be A Reference" with Call_User_Func and Bind Params [duplicate]

Tags:

arrays

php

mysqli

I have been trying to bind an array with a prepared statement for days, I have managed to create the number of ?,? and the i,i these are represented in my code as $params and $type. The problem comes when using call_user_func_array with my code since I haven't managed to make it work, I have tried multiple answers from this site but I haven't got it working.

The full query code is:

$params = implode(',', array_fill(0, count($greaterThan), '?'));
$stmt11 = $mysqli->prepare("SELECT nombre FROM usuarios WHERE id IN (".$params.")");
$type = implode('', array_fill(0, count($greaterThan), 'i'));
$param = implode(",", $greaterThan);
call_user_func_array(array($stmt11, "bind_param"), array_merge(array($type), $greaterThan));
print_r(error_get_last());
$stmt11->execute();
$stmt11->store_result();
$stmt11->bind_result($nombresmayores);
$arraynombresmayores = array();
$stmt11->store_result();
while($stmt11->fetch()){
    $arraynombresmayores[] = $nombresmayores;
}

Where $param are the values separated by comas (just in case you need it). The array I'm trying to bind is $greaterThan, the query works perfectly because I have made some debugging. The error the program outputs is:

Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given

Finally, the content of the array is:

array(2) {
  [0]=>
  int(2)
  [1]=>
  int(4)
}
like image 769
C.Xammar Avatar asked Feb 21 '26 02:02

C.Xammar


1 Answers

if your php version is not outdated you can make it much simper

$params = implode(',', array_fill(0, count($greaterThan), '?'));
$stmt = $mysqli->prepare("SELECT nombre FROM usuarios WHERE id IN ($params)");
$types = str_repeat('i',count($greaterThan));
$stmt->bind_param($types, ...$greaterThan);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($nombresmayores);
$arraynombresmayores = array();
$stmt->store_result();
while($stmt->fetch()){
    $arraynombresmayores[] = $nombresmayores;
}

but better yet use PDO:

$params = implode(',', array_fill(0, count($greaterThan), '?'));
$stmt = $pdo->prepare("SELECT nombre FROM usuarios WHERE id IN ($params)");
$stmt->execute($greaterThan);
$arraynombresmayores = $stmt->fetchAll(PDO::FETCH_COLUMN);

just compare this neat code with that awful mess you have now.

like image 126
Your Common Sense Avatar answered Feb 23 '26 15:02

Your Common Sense



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!