Skip navigation

The following method can be used to easily generate an HTML table from any SQL Result set. The PHP methods used are for Postgres, but you could change them to whatever database backend you use, for example, MySQL, etc.


 * Print out a generic results table from a postgresql result set.
 * Method should work on any result set.

function mk_table_from_SQL($SQLTable) {

	pg_result_seek($SQLTable, 0);	// Rewind the result set to the beginning
	$html = "<table>";		// Write the table opening html
	$html .= "<tr>";		// Write out the column headers

	for ($i=0; $i < pg_num_fields($SQLTable); $i++) {
		$html .= "<th>" . pg_field_name($SQLTable, $i) . "</th>";

	$html .= "</tr>";

	while($row=pg_fetch_array($SQLTable)) {
		// Write out subsequent rows

		$html .= "<tr>";

		for ($i=0; $i < pg_num_fields($SQLTable); $i++) {
			$html .= "<td>$row[$i]</td>";

		$html .= "</tr>\n";

	$html .= "</table>\n";	// End the table

	return $html;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: