Tuesday, November 16, 2010

How to quickly show the results of query in Table format

There are many times when I'm coding when I just want to quickly display the results of a SQL Query either for debugging purposes or until I polish up a nice view for the user. This code will pick out the column names and make column headers in the table for each one.

P.S. This demonstration is for MSSQL, but it will work the same with MySQL (just replace the mssql_ functions with mysql_ functions).

<?php
//connect to your database
mssql_connect('localhost', 'user', 'password');
mssql_select_db('database');

//query your database
$sql = "SELECT * FROM employee_info";
$result = mssql_query($sql);

//only show output if there are records returned
if(mssql_num_rows($result)) {
    echo "<table border=1>"; //start the table
    $th = false; //set a boolean to determine when to show the header
    //loop through the results
    while($row = mssql_fetch_assoc($result)) {
        //display the header row if it hasn't already been shown
        if(!$th) {
            echo "<tr>";
            foreach($row as $key => $data)
                echo "<th>$key</th>";
            echo "</tr>";
            $th = true;
        }
        //start your data row
        echo "<tr>";
        foreach($row as $data)
                echo "<td>$data</td>";
        echo "</tr>";
    }
    echo "</table>"; //end the table
} else {
    echo "There are no results";
}
?>

No comments:

Post a Comment