34

What query do I need to run in PHP to get the structure of a given table in the database? And what query do I need to run to get a list of all the tables?

Teifion
  • 108,121
  • 75
  • 161
  • 195

6 Answers6

46

To get a list of columns for a table, use the DESCRIBE SQL statement. The syntax is as follows:

DESCRIBE TableName

To get a list of tables on the database, use this SQL statement:

SHOW TABLES
MrValdez
  • 8,515
  • 10
  • 56
  • 79
24
$q = mysql_query('DESCRIBE tablename');
while($row = mysql_fetch_array($q)) {
    echo "{$row['Field']} - {$row['Type']}\n";
}

found it at http://www.electrictoolbox.com/mysql-table-structure-describe/

user866339
  • 439
  • 5
  • 15
20

To get the CREATE syntax use

SHOW CREATE TABLE table_name;

Also take a look in the information_schema database. Lots of very useful information about your databases, tables, indexes, etc.

See: How to find all the tables in MySQL with specific column names in them?

Community
  • 1
  • 1
Ken
  • 77,016
  • 30
  • 84
  • 101
4

For get comments of the fields you can use:

SHOW FULL COLUMNS FROM table_name;

Notice keyword FULL, this is what makes MySQL to include privileges and comments info into the response.

rpayanm
  • 6,303
  • 7
  • 26
  • 39
1

Updating with MYSQLI:

Connect with database

function conectadb($banco) 
{
$endereco = "localhost";
$usuario  = "root";
$senha    = "";
try
{
    $con = new mysqli($endereco, $usuario, $senha, $banco);
    $con->set_charset("utf8"); // acentuação
    return $con;
}
catch (Exception $e)
{
    echo "<h1>Falha</h1><br/>";
    echo $e->getMessage();
    die();
}
}

Show column table:

function show_table($tabela)
{
$conexao=conectadb('venda');
$sql = "DESCRIBE $tabela";
$result = $conexao->query($sql);
while ($coluna = $result->fetch_assoc()) 
{
    echo "<p>".$coluna['Field']." - ";
    echo $coluna['Type']."</p>";
}

}

1

$result= mysqli_query($conn, "DESCRIBE your_table");
 while($table = mysqli_fetch_array($result)) 
{ 
  echo($table[0]." ".$table[1]." ". $table[2]." ". $table[3]." ". $table[4]);  
 }

Sean H. Worthington
  • 1,701
  • 15
  • 9
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) will help people understand the reasons for your code suggestion. – Gerhard Feb 02 '22 at 14:27