Listing MySQL tables with PHP
Posted April 9th, 2009 in MySql and PHP
This post shows how to use the MySQL "SHOW TABLES FROM" SQL query to get a list of tables using PHP. This list could either be stored to an array or echoed out to web browser, command line etc.
The example code below uses the raw mysql_* functions but you easily enough use a database abstraction library to achieve more or less the same thing. $server, $login, $password and $db are variables which store the obvious.
mysql_connect($server, $login, $password);
$res = mysql_query("SHOW TABLES FROM $db");
while($row = mysql_fetch_array($res, MYSQL_NUM)) {
echo "$row[0]\n";
}
To instead put the tables into an array do the following:
mysql_connect($server, $login, $password);
$res = mysql_query("SHOW TABLES FROM $db");
$tables = array();
while($row = mysql_fetch_array($res, MYSQL_NUM)) {
$tables[] = "$row[0]";
}
Note that the code examples above pass MYSQL_NUM as the second parameter to the mysql_fetch_array() function. This returns a numeric based array which is easier to work with; an associative array with column names will label the column "Tables_in_$db" where $db is the database name and is a little annoying to work with when doing this sort of thing.
Related posts:
- Hide selected databases in phpMyAdmin (Tuesday, October 21st 2008)
- Hide the information schema in phpMyAdmin (Saturday, October 11th 2008)
- Intialise an array in PHP with default values (Tuesday, October 7th 2008)
- Return information from PHP print_r instead of displaying it (Tuesday, September 30th 2008)
- PHP is not showing any error messages (Tuesday, June 10th 2008)

Comments
blog comments powered by Disqus