bard_the_dragon
bard_the_dragon

Reputation: 33

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?

Upvotes: 2

Views: 4554

Answers (2)

accalton
accalton

Reputation: 381

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

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

if($mysqli->connect_errno)
{
    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 />";
    }
}

$mysqli->close();
?>

Upvotes: 4

Julie Pelletier
Julie Pelletier

Reputation: 1716

The MySQL syntax for those uses the command SHOW which can be used to show the tables in the selected database (SHOW tables;) or output table structure (SHOW tableName;).

Here is functional code to see the tables in the current database so long as you update the connection details (first line of code):

$mysqli = new mysqli("server.com", "userName", "password", "dbName");

if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$query = "SHOW tables;";
$result = $mysqli->query($query);
/* associative array */
$rows = $result->fetch_all(MYSQLI_ASSOC);
var_export($rows);

$result->free();

/* close connection */
$mysqli->close();

Upvotes: 1

Related Questions