1

I store some data from the MySQL database into an array:

$p = $db->query('SELECT * FROM comments;');
while ($row = $p->fetch(PDO::FETCH_ASSOC)) {
   $commentlist[$row['id']] = $row['text'];
}  


  foreach($commentlist as $key => $value) {
      echo $key;
      echo $value;
  }

Now I have access to the values id and text. But I also need to have access to the value image (which is another row in the MySQL database). But how can I store it if I have only two available elements: key and value?

1
  • it will be helpful if you can show sample structure of your table. Commented May 5, 2017 at 11:52

1 Answer 1

2

If you need other fields, then you should store the whole row in $value.

However, PDO is a little more than everyone think. It can give you the desired result in a single call thanks to, fetchAll() method with PDO::FETCH_UNIQUE modifier:

$commentlist = $db->query('SELECT * FROM comments;')->fetchAll(PDO::FETCH_UNIQUE);

Now you can foreach over comments

foreach($commentlist as $id => $value) {
    echo $id;
    echo $value['text'];
    echo $value['image'];
}
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.