If you ever want to show a MySQL database table including data of it, here is a function to acheive it. You got to pass some simple parameters to generate table in your page. Enjoy!
By : CodeKadiya
<?PHP # --------------------------------- # Programmer : CodeKadiya --------- # Email : codekadiya@yahoo.com ---- # --------------------------------- # --------------------------------- # Param 1 : MySQL Host Name # Param 2 : MySQL Username # Param 3 : MySQL Password # Param 4 : MySQL Database # Param 5 : SQL Statement (SELECT)
show_table("localhost","username","password","database","SELECT * FROM table");
function show_table($hostName,$userName,$passWord,$dataBase,$sqlQuery) { # Connect to MySQL $conn=mysql_connect($hostName,$userName,$passWord); # Select Database mysql_select_db($dataBase,$conn); # Validate SQL Statement $array=explode(" ORDER",$sqlQuery); $sqlQuery=$array[0]; if(!strstr($sqlQuery,"SELECT")) die("Invalid Query : SQL statement should be a SELECT statement."); # ORDER records by requested column if($_GET['order']) $sqlQuery=$sqlQuery." ORDER BY ".$_GET['order']; # Execute SQL query $result=mysql_query($sqlQuery) or die("Invalid Query : ".mysql_error()); $row=mysql_fetch_array($result); # Check whether NULL records found if(!mysql_num_rows($result)) die("No records found.");
echo "<table border=1><tr>"; # Make the row for table column names while (list($key, $value) = each($row)) { $i++; if(!($i%2)) echo "<td><b><a href='?order=$key'>$key</a></td>"; } echo "</tr>"; $result=mysql_query($sqlQuery); // Make rows for records while($rec=mysql_fetch_array($result)) { echo "<tr>"; for($i=0;$i<count($rec);$i++) { if($rec[$i]) echo "<td>$rec[$i]</td>"; } echo "</tr>"; } echo "</table>"; } ?>
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.