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!
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:)
Prepared statements are meant to exactly avoid what you're trying to make it do :)
To get this to work you have to apply this step:
It maps the proper string escaping function for your database on each item of
$lastnames
. When done, you insert this value straight into the query, i.e. without using bound parameters.