Reputation: 98
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?
Upvotes: 0
Views: 66
Reputation: 157981
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 like IN (?,?,?,?)
and run it in one query. Something like this (not tested):
$in = trim(str_repeat('?,',count($productid)).",");
$sql = "SELECT name FROM product WHERE id IN ($id)";
$stmt = $db->prepare($sql);
$stmt->execute($productid);
$name = $stmt->fetchAll();
Upvotes: 1