Skip to content
Advertisement

How does while ($row = $result->fetch_object()) work? [closed]

I was watching a tutorial series on PHP MySQLi this morning and I came across a bit of code that the author of the series didn’t bother explain. I have seen this code before but never knew exactly how it works…

while ($row = $result->fetch_object()) {
    // set up a row for each record
    echo "<tr>";
    echo "<td>" . $row->id . "</td>";
    echo "<td>" . $row->firstname . "</td>";
    echo "<td>" . $row->lastname . "</td>";
    echo "<td><a href='records.php?id=" . $row->id . "'>Edit</a></td>";
    echo "<td><a href='delete.php?id=" . $row->id . "'>Delete</a></td>";
    echo "</tr>";
}

I know that its piecing together a table with the results of $result from a MySQL query but what I don’t get is, how does the while loop function with an assignment going on inside the parameters?

I tried to echo out $row = $result->fetch_object() but it didn’t display anything to the screen.

Advertisement

Answer

To debug queries don’t use echo.

Use var_dump() or print_r()

All your query is doing is looping and creating table rows populated with data from an sql table.

The

while ($row = $result->fetch_object()) {

is simply generating a variable $row set to contents of 1 record (technically, with JOINs its more than 1 real “record”, but I doubt your using that here), then while you loop through you are printing the values of the columns with $row->id.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement