Schema Printer

Posted on in: All Posts, My Projects.
Tags:

This is my first php script that will query a MYSQL database. Its pretty simple, but it makes me feel like I’m making progress learning PHP.

<html>
<head>
<style type="text/css">
body *{
 font: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
h1{
 text-align: center;
}
table{
 width: 100%;
 border: 1px solid #000;
}
table td{
 padding: 1px 10px;
 margin: 0;
 border: 1px solid #000;
}
table th{
 padding: 3px 10px;
 text-align: center;
 background-color: #ddd;
 font-weight: bold;
 border: 2px solid #000;
}
#table_output{
 margin: 0 50px;
}
tr:nth-child(odd) { background-color:#eef; }
tr:nth-child(even) { background-color:#fff; }

</style>
</head>
<body>
<?php
$host = "127.0.0.1"; //AKA localhost
$username = "root"; //username
$password = ""; //password for said user
$database = "smleimberg.com"; // database schema to query on said host

$connection = mysql_connect($host, $username, $password) or die(mysql_error());
$selection = mysql_select_db($database) or die(mysql_error());
$tables = mysql_list_tables($database)or die("List tables error: ".mysql_error());
$numTables= mysql_num_rows($tables)or die(mysql_error());

echo "<h1>Schema: ".$database." contains ".$numTables." table(s).</h1>\n";

echo "<ol>";
for($i=0;$i<$numTables;$i++){
 
 $table=mysql_result($tables, $i, 0);
 $rowResult = mysql_query("SELECT * FROM ".$table,$connection) or die("Row Result Error:".mysql_error());
 $numCols= mysql_num_fields($rowResult)or die(mysql_error());
 
 echo "\n<div id=\"table_output\">\n";
 echo "<h2><li>".$table."</li></h2>\n";
 
 // Beginning of Table
 echo "<table>\n";
 
 // Column Heads
 echo "<tr>"; 
 for($j=0;$j<$numCols;$j++){
 echo "<th>".mysql_field_name($rowResult, $j) . "</th>";
 }
 echo "</tr>\n";
 
 //Rows
 while($row = mysql_fetch_array($rowResult)){
 echo "<tr>";
 for($k=0;$k<$numCols;$k++){
 echo "<td>".$row[$k]."</td>";
 }
 echo "</tr>\n";
 }
 // End of Table
 echo "</table>\n";
 echo "</div>\n";
}
echo "</ol>";
?>

</body>
</html>
Logo smleimberg.com