Build HTML Tables Dynamically with PHP Part 1
There is a built-in PHP function which would have really been useful back when using HTML tables for design was popular. Instead of setting up counters and testing when to add the opening and closing tags, we could have just read in the data and displayed it. Let's pretend we're back in the heyday of table hacking and look how the function saves time.
Background
For those unfamiliar with using tables for design, this week's post runs through a quick example. Note that this is a training exercise. CSS is a better solution for what we're about to see. If you can't stomach using tables for design, now is the time to look away.
Let's say we're looking to display the following database information in rows of three:
id | datePosted | firstName | lastName | pictureName |
---|---|---|---|---|
1 | 2013-07-01 | John | Smith | SmithJohn.jpg |
2 | 2013-05-06 | Elroy | Johnson | JohnsonElroy.jpg |
3 | 2013-06-18 | Jake | Bible | BibleJake.jpg |
4 | 2013-07-17 | Steve | Stevenson | StevensonSteve.jpg |
5 | 2013-04-08 | Bill | Smith | SmithBill2.jpg |
In other words, the final result should be a three-column HTML table with however many rows it takes to display everything.
Building HTML Tables
Before grabbing the data, let's create some variables to be used later. One tracks which column is being displayed and the other stores the table output as it's generated.
<?php
//INITIALIZE VARIABLES
$htmlOutput = '';
$colNum = 1;
?>
A MySQL query is used to grab the database information shown earlier.
<?php
//INITIALIZE VARIABLES
$htmlOutput = '';
$colNum = 1;
//GET PICTURE LIST
$sql = "SELECT datePosted, firstName, lastName, pictureName FROM pictureList ORDER BY datePosted DESC";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
}
?>
Within the loop, the column counter will be set to "1" whenever the first column is being added. Since it's the first column, we'll open a row.
<?php
while($row = $result->fetch_assoc()) {
//IF FIRST COLUMN, OPEN NEW ROW
if($colNum == 1) {
$htmlOutput .= '<tr>';
}
}
?>
The main content for the column is added next. So, we'll add the person's name and photo between the HTML column tags.
<?php
while($row = $result->fetch_assoc()) {
//IF FIRST COLUMN, OPEN NEW ROW
if($colNum == 1) {
$htmlOutput .= '<tr>';
}
//ADD PICTURE
$htmlOutput .= "<td><img src='images/{$row['pictureName']}' alt='' /><br />{$row['firstName']} {$row['lastName']}</td>";
}
?>
If the current iteration of the loop just added the third column, the row needs to be closed and the column counter reset to "1". Otherwise, the counter is incremented.
<?php
while($row = $result->fetch_assoc()) {
//IF FIRST COLUMN, OPEN NEW ROW
if($colNum == 1) {
$htmlOutput .= '<tr>';
}
//ADD PICTURE
$htmlOutput .= "<td><img src='images/{$row['pictureName']}' alt='' /><br />{$row['firstName']} {$row['lastName']}</td>";
//IF THIRD COLUMN WAS JUST ADDED
if($colNum == 3) {
$htmlOutput .= '</tr>';
$colNum = 1;
//ELSE...INCREMENT THE COUNTER
} else {
$colNum++;
}
}
?>
Once the looping is done, the table may need to be finalized by adding missing columns and closing the last row. The table can then be displayed.
<?php
while($row = $result->fetch_assoc()) {
//...
}
//CLOSE ANY OPEN ROWS
if($colNum == 2) { $htmlOutput .= '<td></td><td></td></tr>'; }
elseif($colNum == 3) { $htmlOutput .= '<td></td></tr>'; }
//DISPLAY TABLE
print '<table>';
print $htmlOutput;
print '</table>';
?>
Final Code
Note that the following code is missing some essential tags (like <body>). You'll also need to establish a database connection.
<?php
//INITIALIZE VARIABLES
$htmlOutput = '';
$colNum = 1;
//GET PICTURE LIST
$sql = "SELECT datePosted, firstName, lastName, pictureName FROM pictureList ORDER BY datePosted DESC";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
//IF FIRST COLUMN, OPEN NEW ROW
if($colNum == 1) {
$htmlOutput .= '<tr>';
}
//ADD PICTURE
$htmlOutput .= "<td><img src='images/{$row['pictureName']}' alt='' /><br />{$row['firstName']} {$row['lastName']}</td>";
//IF THIRD COLUMN WAS JUST ADDED
if($colNum == 3) {
$htmlOutput .= '</tr>';
$colNum = 1;
//ELSE...INCREMENT THE COUNTER
} else {
$colNum++;
}
}
//CLOSE ANY OPEN ROWS
if($colNum == 2) { $htmlOutput .= '<td></td><td></td></tr>'; }
elseif($colNum == 3) { $htmlOutput .= '<td></td></tr>'; }
//DISPLAY TABLE
print '<table>';
print $htmlOutput;
print '</table>';
?>
Conclusion
For the most part, the code doesn't look too bad. Well, as long as we can get past the fact that HTML tables are being used for design. The code, however, could be a lot simpler. But that will have to wait until next week.
3 Comments
Nice. This is good example for create a table dynamically.
Thanks.
@Muhammed – Sorry about the confusion. $mysqli should hold your database object that was created using MySQLi. More information can be found here:
http://php.net/manual/en/mysqli.quickstart.connections.php
Note that the above code should work with the deprecated mysql_* functions…or PDO. You'll just need to change the MySQLi-specific code.
Hi , thank you for this post! I'm ask a question what is $mysqli ? i try this code and i get a 'undefined variable' warning.
Leave a Comment