Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQLi prepared statements with IN operator [duplicate]

I have to select some rows from the database using IN operator. I want to do it using prepared statement. This is my code:

<?php
$lastnames = array('braun', 'piorkowski', 'mason', 'nash');
$in_statement = '"' . implode('", "', $lastnames) . '"'; //"braun", "piorkowski", "mason", "nash"

$data_res = $_DB->prepare('SELECT `id`, `name`, `age` FROM `users` WHERE `lastname` IN (?)');
$data_res->bind_param('s', $in_statement);
$data_res->execute();
$result = $data_res->get_result();
while ($data = $result->fetch_array(MYSQLI_ASSOC)) {
    ...
}
?>

But returns nothing although all data exists in the database.

And one more: if i pass $in_statement directly to query and execute it, the data will be returned. So the problem appears on preparing.

I was looking for the question in Google but it wasn't' successful. What's wrong with my code?
Thanks for the help!

like image 935
kpotehin Avatar asked Aug 13 '12 17:08

kpotehin


1 Answers

I've recently found the solution for my question. Maybe it's not the best way to do it, but it works nice! Prove me wrong:)

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

foreach($lastnames as $key => $value) //recreate an array with parameters explicitly passing every parameter by reference
    $arParams[] = &$lastnames[$key];

$count_params = count($arParams);

$int = str_repeat('i',$count_params); //add type for each variable (i,d,s,b); you can also determine type of the variable automatically (is_int, is_float, is_string) in loop, but i don't need it
array_unshift($arParams,$int); 

$q = array_fill(0,$count_params,'?'); //form string of question marks for statement
$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();
$result = $data_res->get_result();
while ($data = $result->fetch_array(MYSQLI_ASSOC)) {
    ...
}

$result->free();
$data_res->close();
?>
like image 64
kpotehin Avatar answered Oct 18 '22 12:10

kpotehin