HTML table with ezSQL

When writing an application in PHP, I like to use Justin Vincents ezSQL for database access. ezSQL allows you to write your query and get your results as a PHP object, as shown in the following example:

// Select multiple records from the database and print them out..
$users = $db->get_results("SELECT name, email FROM users");
 
foreach ( $users as $user )
{
            // Access data using object syntax
            echo $user->name;
            echo $user->email;
}

So one common task you might want to do is to present the retrieved result as a table. While the ezSQL library features a debug() method, this should obviously only be used during development. So if you want to display your result as a table, you’ve got to do it yourself and I hereby provide a snippet of code on how to do it…

So after you’ve fetched your result from the database you can use the following method to print a HTML table with your results:

/**
 * Function to draw a HTML table from an ezSQL data object.
 * The columns will be named according to your query
 */
public function drawTable($data) {
	echo '<table>';
	echo '<tr>';
	foreach($data[0] as $column => $value) :
		echo '<th>' . $column . '</th>';
	endforeach;
	echo '</tr>';

	foreach($data as $row) :
		echo '<tr>';
		foreach($row as $column => $value) :
			echo '<td>' . $value . '</td>';
		endforeach;
		echo '</tr>';
	endforeach;
	echo '</table>';
}

While this might not be the most sophisticated piece of code, it works alright. Feel free to use it however you like.