Output a MySQL Query as a basic HTML Table

quote-bg

Ever wanted to just output a MySQL query as a basic HTML table, perhaps with radio buttons with unique identifiers as values? Here's how:

[prism:php] function createTable($id, $pk, $left=FALSE, $right=FALSE) { //Generic code for connecting to a local database mysql_connect('localhost', 'username', 'password'); mysql_select_db("database"); //$result is the variable we pass into the //while loop to output the table rows $result = mysql_query("SELECT * FROM table") or die(mysql_error()); //Initialize $table variable - this will //contain all of the output data $table = ""; //Counter variable used to set the table headers $k = 0; //Initialize head and body variables $body = ""; $head = ""; //Begin looping through $result for each table row while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { //Begin headers of the table. Since mysql_fetch_array // grabs the column names, I can use the array_keys // function to get the headers $keys = array_keys($row); //If you're adding a left radio button, add a blank header //Checking for beginning of database table to add column headers if ($k == 0) { $head.=""; if ($left == TRUE) { $head.=""; } for ($i = 0; $i count($row); $i++) { $head.=""; } if ($right == TRUE) { $head.=""; $head.=""; } } //If you're adding a right radio button, add a blank header //begin creating body content $body .= ""; //set row primary key value $primary_key = $row[$pk]; //If you're adding a left radio button, add it here if ($left == TRUE) { $body.=""; } //loop through each cell for the row and output the value in a table cell for ($j = 0; $j count($row); $j++) { $body.=""; } //If you're adding a right radio button, add it here if ($right == TRUE) { $body.=""; $body.=""; $k++; } $table .= $head . $body; $table .="" . $keys[$i] . "value='$primary_key' />".$row[$keys[$j]]."value='$primary_key' />"; return $table; } //Call the function here. Last two parameters display left and/or right radio buttons print createTable("tbl-data", "ID", false, false); [/prism:php]