I have a pretty standard database like:
id | name | last_name | gender
-----------------------------------------------
1 | John | Doe | Male
2 | Jane | Smith Dolores Clayborne | Female
3 | Paul | Paulson | Male
and I want to display it in a table, but every row in the DB needs to be a column in HTML table:
id | 1 | 2 | 3
---------------------------------------------
name | John | Jane | Paul
---------------------------------------------
last_name | Doe | Smith | Paulson
| | Dolores |
| | Clayborne |
---------------------------------------------
gender | Male | Female | Male
If I go with:
foreach($data as $row) {
echo "<tr><td>" . $row->id . "</td></tr>";
echo "<tr><td>" . $row->name . "</td></tr>";
echo "<tr><td>" . $row->last_name . "</td></tr>";
echo "<tr><td>" . $row->gender . "</td></tr>";
}
I get all the data in one long column. How do I break the column after every SQL row?
Note: $data is an array of objects that contain properties with the field values (you can probably figure that out from the example).
EDIT:
I found the solution, see my answer, it’s simple and elegant.
I figured it out, turns out it’s a pretty simple solution with few cycles and pre-populating an array before writing rows and cells.
I tested it, works like a charm. 😉 It might be useful for someone, so here it is: