Listing table names in php

PHP MySQL Functions to list table names in a databases

We can list tables present in a database by using this query
SHOW TABLES
Using this we can develop a PHP script to display all tables.
query("SHOW TABLES");

while ($row = $result->fetch(PDO::FETCH_NUM)) {
echo $row[0]."
"; } ?>
We can display tables of a database by changing the above query.
SHOW TABLES in PDO
Above query will return all the tables of the database pdo
Similarly if we want to list all the tables starting with char t then we can use LIKE command. Here is the query.
SHOW TABLES from pdo LIKE 't%'
Above query can be placed inside the PHP code (shown above ) to display matching tables. For easy understanding here again the php code.
query("SHOW TABLES from pdo LIKE 't%'");

while ($row = $result->fetch(PDO::FETCH_NUM)) {
echo $row[0]."
"; } ?>
Using MySQLI
if($stmt = $connection->query("SHOW TABLES")){
  echo "No of records : ".$stmt->num_rows."
"; while ($row = $stmt->fetch_array()) { echo $row[0]."
"; } }else{ echo $connection->error; }

mysql_list_tables()

We can display a list of tables present in a database by using mysql_list_tables() function. Connection has to be established before call of this function. The result pointer returned by this function is used by mysql_tablename() function to display the name of the tables.


$list = mysql_list_tables ("sql_tutorial");
$i = 0;
while ($i < mysql_num_rows ($list)) {
$tb_names[$i] = mysql_tablename ($list, $i);
echo $tb_names[$i] . "
";
$i++;
}
?>


Listing table names in php


Listing table names in php

plus2net.com


Listing table names in php
More on PHP MySQL functions

Vicente Carlos

20-05-2012

I1m loving your site! Very usefull. Thanks

ram

02-11-2012

this website is very useful. thank you

Deepak

22-04-2015

Helpful website. But Please also include a demo of code if possible. Thank you for helping coders.

(PHP 4, PHP 5)

mysql_list_tablesList tables in a MySQL database

Warning

This function was deprecated in PHP 4.3.0, and it and the entire original MySQL extension was removed in PHP 7.0.0. Instead, use either the actively developed MySQLi or PDO_MySQL extensions. See also the MySQL: choosing an API guide. Alternatives to this function include:

  • SQL Query: SHOW TABLES FROM dbname

Description

mysql_list_tables(string $database, resource $link_identifier = NULL): resource|false

This function is deprecated. It is preferable to use mysql_query() to issue an SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead.

Parameters

database

The name of the database

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

A result pointer resource on success or false on failure.

Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array().

Changelog

VersionDescription
4.3.7 This function became deprecated.

Examples

Example #1 mysql_list_tables() alternative example

$dbname 'mysql_dbname';

if (!

mysql_connect('mysql_host''mysql_user''mysql_password')) {
    echo 
'Could not connect to mysql';
    exit;
}
$sql "SHOW TABLES FROM $dbname";
$result mysql_query($sql);

if (!

$result) {
    echo 
"DB Error, could not list tables\n";
    echo 
'MySQL Error: ' mysql_error();
    exit;
}

while (

$row mysql_fetch_row($result)) {
    echo 
"Table: {$row[0]}\n";
}
mysql_free_result($result);
?>

Notes

Note:

For backward compatibility, the following deprecated alias may be used: mysql_listtables()

See Also

  • mysql_list_dbs() - List databases available on a MySQL server
  • mysql_tablename() - Get table name of field

daveheslop (dave heslop)

17 years ago

Worth noting for beginners: using a row count to test for the existence of a table only works if the table actually contains data, otherwise the test will return false even if the table exists.

NewToPHP_Guy at Victoria dot NOSPAM dot com

19 years ago

The example by PHP-Guy to determine if a table exists is interesting and useful (thanx), except for one tiny detail.  The function 'mysql_list_tables()' returns table names in lower case even when tables are created with mixed case.  To get around this problem, add the 'strtolower()' function in the last line as follows:

return(in_array(strtolower($tableName), $tables));

bimal at sanjaal dot com

9 years ago

A better alternative to mysql_list_tables() would be the following mysql_tables() function.

/**
* Better alternative to mysql_list_tables (deprecated)
*/
function mysql_tables($database='')
{
   
$tables = array();
   
$list_tables_sql = "SHOW TABLES FROM {$database};";
   
$result = mysql_query($list_tables_sql);
    if(
$result)
    while(
$table = mysql_fetch_row($result))
    {
       
$tables[] = $table[0];
    }
    return
$tables;
}
# Usage example
$tables = mysql_tables($database_local);
?>

coffee at hayekheaven dot net

20 years ago

Even though php guy's solution is probably the fastest here's another one just for the heck of it...
I use this function to check whether a table exists. If not it's created.

mysql_connect("server","usr","pwd")
    or die("Couldn't connect!");
mysql_select_db("mydb");

$tbl_exists = mysql_query("DESCRIBE sometable");
if (!$tbl_exists) {
mysql_query("CREATE TABLE sometable (id int(4) not null primary key,
somevalue varchar(50) not null)");
}

kroczu at interia dot pl

15 years ago

// here is a much more elegant method to check if a table exists ( no error generate)

if( mysql_num_rows( mysql_query("SHOW TABLES LIKE '".$table."'")))
{
//...
}

?>

mrkvomail at centrum dot cz

16 years ago

You can also do this with function mysql_query(). It's better because mysql_list_tables is old function and you can stop showing errors.

function mysql_table_exists($dbLink, $database, $tableName)
{
   $tables = array();
   $tablesResult = mysql_query("SHOW TABLES FROM $database;", $dbLink);
   while ($row = mysql_fetch_row($tablesResult)) $tables[] = $row[0];
    if (!$result) {
    }
   return(in_array($tableName, $tables));
}

daevid at daevid dot com

19 years ago

I was in need of a way to create a database, complete with tables from a .sql file. Well, since PHP/mySQL doesn't allow that it seems, the next best idea was to create an empty template database and 'clone & rename it'. Guess what? There is no mysql_clone_db() function or any SQL 'CREATE DATABASE USING TEMPLATEDB' command. grrr...

So, this is the hack solution I came up with:

$V2DB = "V2_SL".$CompanyID;

$result = mysql_create_db($V2DB, $linkI);
if (!$result) $errorstring .= "Error creating ".$V2DB." database
\n".mysql_errno($linkI).": ".mysql_error($linkI)."
\n";

mysql_select_db ($V2DB, $linkI) or die ("Could not select ".$V2DB." Database");

//You must have already created the "V2_Template" database.
//This will make a clone of it, including data.

$tableResult = mysql_list_tables ("V2_Template");
while ($row = mysql_fetch_row($tableResult))
{
    $tsql = "CREATE TABLE ".$V2DB.".".$row[0]." AS SELECT * FROM V2_Template.".$row[0];
    echo $tsql."
\n";
    $tresult = mysql_query($tsql,$linkI);
    if (!$tresult) $errorstring .= "Error creating ".$V2DB.".".$row[0]." table
\n".mysql_errno($linkI).": ".mysql_error($linkI)."
\n";
}

thebitman at attbi dot com

19 years ago

okay everybody, the fastest, most accurate, safest method:

function mysql_table_exists($table, $link)
{
     $exists = mysql_query("SELECT 1 FROM `$table` LIMIT 0", $link);
      if ($exists) return true;
     return false;
}

Note the "LIMIT 0", I mean come on, people, can't get much faster than that! :)
As far as a query goes, this does absolutely nothing. But it has the ability to fail if the table doesnt exist, and that's all you need!

cdarklock at darklock dot com

19 years ago

Actually, the initially posted SELECT COUNT(*) approach is flawless. SELECT COUNT(*) will provide one and only one row in response unless you can't select from the table at all. Even a brand new (empty) table responds with one row to tell you there are 0 records.

While other approaches here are certainly functional, the major problem comes up when you want to do something like check a database to ensure that all the tables you need exist, as I needed to do earlier today. I wrote a function called tables_needed() that would take an array of table names -- $check -- and return either an array of tables that did not exist, or FALSE if they were all there. With mysql_list_tables(), I came up with this in the central block of code (after validating parameters, opening a connection, selecting a database, and doing what most people would call far too much error checking):

if($result=mysql_list_tables($dbase,$conn))
{   // $count is the number of tables in the database
    $count=mysql_num_rows($result);
    for($x=0;$x<$count;$x++)
    {
        $tables[$x]=mysql_tablename($result,$x);
    }
    mysql_free_result($result);
    // LOTS more comparisons here
    $exist=array_intersect($tables,$check);
    $notexist=array_diff($exist,$check);
    if(count($notexist)==0)
    {
        $notexist=FALSE;
    }
}

The problem with this approach is that performance degrades with the number of tables in the database. Using the "SELECT COUNT(*)" approach, performance only degrades with the number of tables you *care* about:

// $count is the number of tables you *need*
$count=count($check);
for($x=0;$x<$count;$x++)
{
    if(mysql_query("SELECT COUNT(*) FROM ".$check[$x],$conn)==FALSE)
    {
        $notexist[count($notexist)]=$check[$x];
    }
}
if(count($notexist)==0)
{
    $notexist=FALSE;
}

While the increase in speed here means virtually nothing to the average user who has a database-driven backend on his personal web site to handle a guestbook and forum that might get a couple hundred hits a week, it means EVERYTHING to the professional who has to handle tens of millions of hits a day... where a single extra millisecond on the query turns into more than a full day of processing time. Developing good habits when they don't matter keeps you from having bad habits when they *do* matter.

Anonymous

19 years ago

/*
   Function that returns whole size of a given MySQL database
   Returns false if no db by that name is found
*/

  function getdbsize($tdb) {
    $db_host='localhost';
    $db_usr='USER';
    $db_pwd='XXXXXXXX';
    $db = mysql_connect($db_host, $db_usr, $db_pwd) or die ("Error connecting to MySQL Server!\n");
    mysql_select_db($tdb, $db);

    $sql_result = "SHOW TABLE STATUS FROM " .$tdb;
    $result = mysql_query($sql_result);
    mysql_close($db);

    if($result) {
        $size = 0;
        while ($data = mysql_fetch_array($result)) {
             $size = $size + $data["Data_length"] + $data["Index_length"];
        }
        return $size;
    }
    else {
        return FALSE;
    }
  }

?>

/*
   Implementation example
*/

  $tmp = getdbsize("DATABASE_NAME");
  if (!$tmp) { echo "ERROR!"; }
  else { echo $tmp; }
?>

Anonymous

16 years ago

Getting the database status:
// Get database status by DtTvB
// Connect first
mysql_connect   ('*********', '*********', '********');
mysql_select_db ('*********');

// Get the list of tables
$sql  = 'SHOW TABLES FROM *********';
if (!$result = mysql_query($sql)) { die ('Error getting table list (' . $sql . ' :: ' . mysql_error() . ')'); }

// Make the list of tables an array
$tablerow = array();
while ($row = mysql_fetch_array($result)) { $tablerow[] = $row; }

// Define variables...
$total_tables       = count($tablerow);
$statrow            = array();
$total_rows         = 0;
$total_rows_average = 0;
$sizeo              = 0;

// Get the status of each table
for ($i = 0; $i < count($tablerow); $i++) {
    // Query the status...
    $sql = "SHOW TABLE STATUS LIKE '{$tablerow[$i][0]}';";
    if (!$result = mysql_query($sql)) { die ('Error getting table status (' . $sql . ' :: ' . mysql_error() . ')'); }
    // Get the status array of this table
    $table_info = mysql_fetch_array($result);
    // Add them to the total results
    $total_rows         += $table_info[3];
    $total_rows_average += $table_info[4];
    $sizeo              += $table_info[5];
}

// Function to calculate size of the file
function c2s($bs) {
         if ($bs < 964)     { return round($bs)           . " Bytes"; }
    else if ($bs < 1000000) { return round($bs/1024,2)    . " KB"   ; }
    else                    { return round($bs/1048576,2) . " MB"   ; }
}

// Echo the result!!!!!!!!!
echo "{$total_rows} rows in {$total_tables} tables";
echo "
Average size in each row: " . c2s($total_rows_average/$total_tables);
echo "
Average size in each table: " . c2s($sizeo/$total_tables);
echo "
Database size: " . c2s($sizeo);

// Close the connection
mysql_close();
?>

wbphfox at xs4all dot nl

19 years ago

Here is a way to show al the tables and have the function to drop them...

echo "

";
//this is the connection file for the database....
$connectfile = "connect.php";
require
$connectfile;$dbname = 'DATABASE NAME';$result = mysql_list_tables($dbname);

echo

"";
echo 
" ";
echo   
"";
echo   
"";
echo 
"";

      if (!

$result) {
        print
"DB Error, could not list tables\n";
        print
'MySQL Error: ' . mysql_error();
        exit;
    }

        while (

$row = mysql_fetch_row($result)) {
        echo
"";
echo   
"";

echo

"";

echo

"";

                    }

mysql_free_result($result);//Delete
if($action=="delete")
{
$deleteIt=mysql_query("DROP TABLE $table");
if(
$deleteIt)
{
echo
"The table \"";
echo
"$table\" has been deleted with succes!
"
;
}
else
{
echo
"An error has occured...please try again
"
;
}
}
?>

mail at thomas-hoerner dot de

19 years ago

You can also use mysql_fetch_object if you consider a specialty: The name of the object-var is

Tables_in_xxxxx

where xxxxx is the name of the database.

i.e. use

$result = mysql_list_tables($dbname);
$varname="Tables_in_".$dbname;
while ($row = mysql_fetch_object($result)) {
   echo $row->$varname;
};

How can I get all table names in a database in PHP?

If you have to use PHP, here's a very simple demonstration. Try this code after connecting to your database: $result = mysql_query("show tables"); // run the query and assign the result to $result while($table = mysql_fetch_array($result)) { // go through each row that was returned in $result echo($table[0] .

How do I get a list of table names in MySQL?

The syntax to get all table names with the help of SELECT statement. mysql> use test; Database changed mysql> SELECT Table_name as TablesName from information_schema. tables where table_schema = 'test'; Output with the name of the three tables.

How can I see all tables in a database?

Then issue one of the following SQL statement:.
Show all tables owned by the current user: SELECT table_name FROM user_tables;.
Show all tables in the current database: SELECT table_name FROM dba_tables;.
Show all tables that are accessible by the current user:.

How can I see all databases in PHP?

By using mysql_db_list() function we can get the result set and by using a pointer to this result set we can get the list of all the database. With this and using the code below we can list all the databases hosted on the mysql server. Here is the code, ensure that connection is available to the server.

Table name:Delete?
";
           print
"$row[0]\n";
echo   
"
";
echo   
"$PHP_SELF?action=delete&table=";
         print
"$row[0]\n";
echo   
"\">Yes?
"
;

echo

"