tags:

views:

549

answers:

3

When using PHP PDO to access the database, is there a way to list all the tables in a database?

Something like mysql_list_tables() is whats needed.

+2  A: 

Hi,

What about using a SQL query that does something like this :

show tables

Or, if needed, specifying the database :

show tables from crawler

And, if you only want to get some tables :

show tables from crawler like 'site%'


Actually, even if the mysql_list_tables() function exists, its manual page states :

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

So, this should be quite OK with PDO, I'm guessing.


And, testing with PDO :

$db = new PDO('mysql:dbname=crawler;host=127.0.0.1', 'crawler', 'crawler');
$result = $db->query("show tables");
while ($row = $result->fetch(PDO::FETCH_NUM)) {
    var_dump($row[0]);
}

I'm getting this kind of output :

string 'headers' (length=7)
string 'headers_sites' (length=13)
string 'headers_sites_0' (length=15)
...
string 'headers_sites_7' (length=15)
string 'reporting_sites_servers_software' (length=32)
string 'servers' (length=7)
string 'sites' (length=5)
string 'sites_0' (length=7)
...
string 'sites_servers' (length=13)
string 'sites_software' (length=14)
string 'software' (length=8)

Which fits with the tables I actually have in this database.

Pascal MARTIN
Yes. This will work as long as the "show tables" query syntax is valid for all the PDO supported database drivers. Is this the case?
saintsjd
For example, Postgres uses "\dt" to list tables and not "Show Tables". So if our goal is cross-database compatibility (using PDO), then this way will not work.
saintsjd
@saintsjd : probably not, unfortunatly :-( ;; going through the sources of the Doctrine ORM framework, the query used to list the tables of a DB is a bit more complicated for MsSQL, more complicated again for SQLite, and even more complicated for PgSQL :-(
Pascal MARTIN
If achieving cross-database compatibility is your real goal, you'll probably better using something like Doctrine (which implements lots of stuff related to DB-compatibility), might I add : PDO is nice, but it only abstract some differences (like not having to use mysqli_* or pg_* or ...) ;; it doesn't abstract the differences between SQL syntaxes that each DB engine understand.
Pascal MARTIN
That's why the docu at http://uk.php.net/manual/en/intro.pdo.php says: "PDO does not provide a database abstraction"
VolkerK
A: 

If you want to do this in a cross-platform way, look into Zend Framework's Zend_Db, which provides the listTables() method

notJim
A: 

If you want a portable way to query for the schema, you can use the ansi standard INFORMATION_SCHEMA

troelskn