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.
PDO refers to PHP Data Object, which is a PHP extension that defines a lightweight and consistent interface for accessing a database in PHP. It is a set of PHP extensions which provide a core PDO class and database-specific driver.
Fetch data from a result set by calling one of the following fetch methods: To return a single row from a result set as an array or object, call the PDOStatement::fetch method. To return all of the rows from the result set as an array of arrays or objects, call the PDOStatement::fetchAll method.
Show Tables of the database Php require "config. php"; // Database Connection $result = $dbo->query("SHOW TABLES"); while ($row = $result->fetch(PDO::FETCH_NUM)) { echo $row[0].
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?
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 aSQL 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.
If you want a portable way to query for the schema, you can use the ansi standard INFORMATION_SCHEMA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With