Mysqli prepared statement with multiple values for IN clause

  1. Comments

Before running any query with mysqli, make sure you've got a properly configured mysqli connection variable that is required in order to run SQL queries and to inform you of the possible errors.

Imagine you've got an array of values that you want to use in the IN() clause in your SQL query.

There are several tricks that would help us in this challenge.

Here is the code:

$array = [1,2,3]; // our array
$in  str_repeat('?,'count($array) - 1) . '?';
$sql "SELECT * FROM table WHERE column IN ($in)";
$stmt  $mysqli->prepare($sql);
$types str_repeat('s'count($array));
$stmt->bind_param($types, ...$array);
$Stmt->execute();
$result $stmt->get_result(); // get the mysqli result
$data $result->fetch_all(MYSQLI_ASSOC); // fetch data   

Related articles: