Param Bind with Array - PHP and Mysqli

Asked

Viewed 629 times

3

I have the code:

<?php

$clientes = implode(', ', $clientes);

$busca = $mysqli->prepare("SELECT nome FROM clientes WHERE id IN (?)");
$busca->bind_param("s", $clientes);
$busca->execute();
$busca->bind_result($nome);
$busca->store_result();

if($busca_num_rows() > 0){

   while($busca->fetch()){
    
        echo $nome . "<br>";

   }

}

?>

Remembering that the variable $clientes is an array that takes the following values

2, 15, 78, 93

ie, I want to recover the names of customers with the above id’s.

My code even works, but it only returns me a client (the client with id 2).

Remembering I tried it this way and it worked:

$busca = $mysqli->prepare("SELECT nome FROM clientes WHERE id IN ($clientes)");

but I don’t want to concatenate the variable inside the query.

How to proceed in this case?

  • removes the bind_param("s", $clientes) and changes to $busca->execute($clientes)

  • 1

    I tried with $search->execute($clients), but returned the following error: Warning: mysqli_stmt::execute() expects Exactly 0 Parameters, 1 Given in /var/www/.../query.php on line 122

  • see if this is http://php.net/manual/en/mysqli-stmt.bind-param.php

  • from what I’ve researched here, the correct is WHERE id IN ($clientes) even

  • 1

    Yes, but it’s not a proper practice to do. I’m just looking for a way to pass these parameters through the mysqli pointer

  • 1

    And when I var_dum($mysqli); it returns Commands out of Sync; you can’t run this command now

  • makes a test, if you put the number of ? equal to the number of fields of the right array?

  • Possible duplicate of Select in Mysql with an array

Show 5 more comments

1 answer

1


There is no bind of array, you need to place all question points dynamically, one for each item of the array:

$clientes = [2, 15, 78, 93];
$queryParameters = join(',', array_fill(0, count($clientes), '?'));
$busca = $mysqli->prepare("SELECT nome FROM clientes WHERE id IN($queryParameters)");
$busca->execute($clientes);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.