MySQLi Prepared Statements with the IN Operator
In database queries, the IN operator allows you to search for specific values within a list. When using MySQLi prepared statements with the IN operator, it is crucial to follow proper syntax to ensure accurate results.
In your provided code, you are encountering an issue where the query returns no results, despite the existence of matching data in the database. This is likely due to an error in the preparation step.
The solution, as you discovered, involves explicitly passing each parameter by reference using the call_user_func_array() function. This is because the bind_param() method expects parameters to be passed directly by value.
By passing parameters by reference, MySQLi accurately retrieves the values and executes the query correctly. Here's an example of the modified code:
$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();
By making this modification, the prepared statement will execute as expected and return the desired results.
The above is the detailed content of How to Correctly Use MySQLi Prepared Statements with the IN Operator?. For more information, please follow other related articles on the PHP Chinese website!