I have an array: productid = [1,2]. Now I want to fetch data from product table by using this part of code:
$sql = 'SELECT name FROM product WHERE id=:id';
$s = $pdo->prepare($sql);
foreach($productid as $id)
{
$s->bindValue(':id', $id);
$s->execute();
}
when I returned the names as follow:
foreach($s as $row)
{
$name[] = array(
'name' => $row['name']
);
}
I just got the product name of second id and didn’t get both names.
What’s the problem?
You’ve got to put your
$name[] = $row['name'];(yes, that’s right notation) code inside of the foreach loop, as well as code that actually fetches the data.You may also form a
IN()statement that should be looks likeIN (?,?,?,?)and run it in one query. Something like this (not tested):