Bind Param with Array – PHP and MySQLi

Question:

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 $clientes variable is an array that takes the following values

2, 15, 78, 93

that is, I want to retrieve the names of the clients with the id's above.

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

Remembering that I tried the following 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?

Answer:

There is no array bind , you need to dynamically place all the question marks, one for each item in 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);
Scroll to Top
AllEscort