Hamed Ghaderi
Hamed Ghaderi

Reputation: 98

Retrive an array stored in database using PDO

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

Answers (1)

Your Common Sense
Your Common Sense

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

Related Questions