Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of mysql_list_tables in PHP PDO?

Tags:

php

pdo

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.

like image 371
saintsjd Avatar asked Sep 20 '09 18:09

saintsjd


People also ask

What is PDO method in PHP?

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.

How does PHP PDO fetch data?

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.

How show all tables in MySQL using PHP?

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].

How can view the structure of table in PHP?

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?


2 Answers

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.

like image 118
Pascal MARTIN Avatar answered Sep 25 '22 03:09

Pascal MARTIN


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

like image 34
troelskn Avatar answered Sep 24 '22 03:09

troelskn