0

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?

3
  • Try using an IN() statement. WHERE id IN (:id). // Edit: I think PDO doesn't support binding arrays as argument though. You probably have to create a comma-separated string of the ids and bind that string. Commented Jan 14, 2013 at 10:06
  • @DanielM it won't work either Commented Jan 14, 2013 at 10:08
  • Looks like the title contradicts with question body. It seems that there are no arrays stored in your table. Commented Jan 14, 2013 at 10:11

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.