Francesca
Francesca

Reputation: 28138

Output multiple results with mysqli_fetch_assoc

What's the best way to output all results from a SELECT query?

if ($result = mysqli_query($con, "SELECT name,pic_url FROM accounts")) {
    $data = mysqli_fetch_assoc($result);
    var_dump($data);
    mysqli_free_result($result);
}

At present dumping of $data only outputs one result, even though a quick check of mysqli_num_rows() shows two results (and there are two rows in the table).

What's the best way to output this data?

I'm essentially looking to output the name field and the pic_url for each row so I was hoping to receive my results as an array which I can then loop through using foreach

Upvotes: 0

Views: 427

Answers (2)

Ashique C M
Ashique C M

Reputation: 683

Use simple while loop and store in an array:

if ($result = mysqli_query($con, "SELECT name,pic_url FROM accounts")) 
{    
  while ($data[] = mysqli_fetch_assoc($result));
}

Upvotes: 1

vaso123
vaso123

Reputation: 12391

you need to use a loop.

while ($data = mysqli_fetch_assoc($result)) {
    var_dump($data);
}

Upvotes: 2

Related Questions