Using msqli_fetch_assoc

Hello everyone,

I’m trying to work with the data from MySQL and format it into a table to be displayed in html and later styled. Couple of questions I came accross:

  1. Should I be using fetch_objects or fetch_assoc/fetch_array for this? Should I export it to json? Do you guys have any preferences?

  2. I stole this bit of code (below) from the web and I just would like to fully understand it before I use it. From what I’ve read, I understand that a while loop works here because mysqli_fetch_assoc returns false if there are no more rows so you dont need a counter in a For loop (what I originally expected for this). My question is how can you store an entire array ($row) inside of an index of another array ($result_array), as thats what this code seems to be doing? mysqli_fetch_array should return a bunch of values associated with the different columns. So if I had a row in a DB table like this: 1, John, Doe, 34 (id, first_name, last_name, age); and you put that into an array like in the code below, $row[0] would be 1, $row[1] would be John, and $row[3] would be 34.

What is $result_array = $row doing exactly in this example, as im not familiar with the specific syntax here?

$query = "SELECT * FROM database;
$result = mysqli_query($query) or die (“Some Error Handeling”);

$result_array = array();
while($row = mysqli_fetch_assoc($result))
{
    $result_array[] = $row;
}

Basically I just need to be able to store all the information to echo into divs or table tags so I can style the table. Thanks!

I don’t really get the code you stole.
But something like this would work to build table rows:-

$result = mysqli_query($con, "SELECT id, name, age FROM table ORDER BY name");
while($row = mysqli_fetch_array($result)) {
   echo '<tr><td>'.$row['id'].'</td><td>'.$row['name'].'</td><td>'.$row['age'].'</td></tr>';
}

I find it easier to work with named keys.

No.

what is $result_array = $row doing exactly in this example

You can always store an array as a member of another array. And get it back from foreach:

foreach($result_array as $row) {
     // here you have your $row back, sound and safe
}

Okay, makes sense, but could you explain that syntax a little bit further? As in, how come you dont need to specify an index? Im just so used to the For loop style where you would have an incremented index variable and say:

$i = 1;
$i++;
$result_array[i] = $row.

How does the computer know to put $row in the next available index when you say $result_array? Or is that exactly what leaving the brackets empty does?

Because the syntax does that.

No offence, but I think that reading this page will give you answers to all your questions:
http://php.net/manual/en/language.types.array.php

1 Like

Awesome, thank you!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.