bard_the_dragon bard_the_dragon - 2 years ago 130
SQL Question

How do I use mysqli to print out the names of the tables in a database and the columns in those tables in php?

I just need to know how to print out the table names and columns, everything I try doesn't work even though this is apparently very simple. I've looked everywhere and I can't find anything that will print out the columns. Can anyone help?

Answer Source

The following code should pull out the information you're after.

$mysqli = new mysqli("hostname", "username", "password", "database");

    echo "Error connecting to database.";

// Gather all table names into an array.

$query = "SHOW TABLES";

$result = $mysqli->query($query);
$tables = $result->fetch_all();

// Step through the array, only accessing the first element (the table name)
// and gather the column names in each table.
foreach($tables as $table)
    echo "<h2>" . $table[0] . "</h2>";

    $query = "DESCRIBE " . $table[0];
    $result = $mysqli->query($query);

    $columns = $result->fetch_all();

    foreach($columns as $column)
        echo $column[0] . "<br />";

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download