Home > Database > Mysql Tutorial > How to Properly Use MySQLi Prepared Statements with the IN Operator?

How to Properly Use MySQLi Prepared Statements with the IN Operator?

Mary-Kate Olsen
Release: 2024-12-17 11:00:25
Original
818 people have browsed it

How to Properly Use MySQLi Prepared Statements with the IN Operator?

MySQLi Prepared Statements with IN Operator

This article addresses the issue of selecting rows from a database using the IN operator and prepared statements in MySQLi. The initial code provided by the original poster:

$data_res = $_DB->prepare('SELECT `id`, `name`, `age` FROM `users` WHERE `lastname` IN (?)');
$data_res->bind_param('s', $in_statement);
$data_res->execute();
Copy after login

failed to return any results, despite the data existing in the database.

The solution involves manually binding each parameter by reference:

$lastnames = array('braun', 'piorkowski', 'mason', 'nash');
$arParams = array();

foreach($lastnames as $key => $value)
    $arParams[] = &$lastnames[$key];

$count_params = count($arParams);

$int = str_repeat('i',$count_params);
array_unshift($arParams,$int);

$q = array_fill(0,$count_params,'?');
$params = implode(',',$q);

$data_res = $_DB->prepare('SELECT `id`, `name`, `age` FROM `users` WHERE `lastname` IN ('.$params.')');
call_user_func_array(array($data_res, 'bind_param'), $arParams);
$data_res->execute();
Copy after login

This approach allows for the correct execution of the prepared statement with the IN operator, ensuring that all data matching the input array is returned from the database.

The above is the detailed content of How to Properly Use MySQLi Prepared Statements with the IN Operator?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template