Equivalent of mysql_list_tables in PHP PDO?

你。 提交于 2020-01-30 05:10:15

问题


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.


回答1:


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.




回答2:


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




回答3:


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




回答4:


$alltables=$db->query("SHOW TABLES",PDO::FETCH_NUM);

while($result=$alltables->fetch()){

echo $result[0].'<br/>';
}

This is the exact code you want, I guess.



来源:https://stackoverflow.com/questions/1451720/equivalent-of-mysql-list-tables-in-php-pdo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!