Perhaps the most popular way to lay out database results is using HTML tables where each row in the database is a row in the table, and each column in the database is a column in the table. In order to give you a head start in this common task, here's an example of table printing in action. The SQL schema used is this:
CREATE TABLE dogbreeds (ID INT AUTO_INCREMENT PRIMARY KEY, Name CHAR(50), Size CHAR(10), Info CHAR(50));
Go ahead and add your own fields to that to fill it up, then create a script with the following code:
<?php
$db = mysqli_connect("localhost", "phpuser", "alm65z", "phpdb");
$result = mysqli_query($db, "SELECT Name, Size, Info FROM dogbreeds ORDER BY Name;");
if (mysqli_num_rows($result)) {
print "<table=\"1\"><tr style=\"font-weight: bold;\"><td>Breed</td><td>Size</td><td>Info</td></tr>";
while($row = mysqli_fetch_assoc($result)) {
extract($row);
print "<tr><td>$Name</td><td>$Size</td><td>$Info</td></tr>";
}
print "</table>";
}
?>
As you can see, it is the same "iterating through mysqli_fetch_assoc() " approach we've used previously, but now we're using it to create an HTML table row by row.
Want to learn PHP 7?
Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!