Technology TidBits

Answers to various technical questions on php programming, mysql, linux, and many more categories.



Add comment:
Name:
Email:
Comment: *
(Use BBcode - No HTML)


You MUST answer this simple math equation - to prevent spammers: 7 + 3 =  


How can I get mysql table definitions in my php script?

Last updated: 07/01/2009
This will dump all the tables and fields in your database, showing the field types, and other attributes.  Useful for building something bigger, or when you don't have command line access to the database to see what the structure looks like.

<?
$db_user = "user";
$db_pass = "password";
$db_database = "database";
$db_host = "localhost";

$db = mysql_connect($db_host, $db_user, $db_pass);
if (!$db) {
   die('Could not connect: ' . mysql_error());
}

mysql_select_db($db_database, $db);


$tables = mysql_query("show tables",$db);

while($table = mysql_fetch_array($tables)) {
        print "<b>Table: ".$table[0]."</b><br>n";
        $result = mysql_query("SHOW COLUMNS FROM ".$table[0],$db);
        if (mysql_num_rows($result) > 0) {
          print "<ul>";
          while ($row = mysql_fetch_assoc($result)) {
                if($row['Null'] == "YES") {
                        $null = "NULL";
                }
                else {
                        $null = "NOT NULL";
                }
          print "<b>".$row['Field']."</b> ".$row['Type']." $null ".$row['Key']." ".$row['Extra']." ".$row['Default']."<br>\n";
           }
          print "</ul>";
        }
}
mysql_close($db);
?>




Powered by KnowledgebasePublisher 1.1
Superb Internet
Content provided by Roberts WebForge, Inc.