Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a list of MySQL databases in PHP using PDO?

Tags:

php

mysql

pdo

I wonder how can I get the list of MySQL databases in PHP using PDO without having to connect to a database first ( I mean no dbname in dsn )?

Usually I used to use the function mysql_list_dbs() but I no longer use mysql this way.

like image 236
taabouzeid Avatar asked Apr 23 '11 18:04

taabouzeid


People also ask

How show all databases in MySQL PHP?

Use SHOW DATABASE query in place of mysql_db_list(). By using mysql_db_list() function we can get the result set and by using a pointer to this result set we can get the list of all the database. With this and using the code below we can list all the databases hosted on the mysql server.

How do I select a database in PDO?

To select data from a table using PDO, you can use: The query() method of a PDO object. Or a prepared statement.

Does PDO work with MySQL?

PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases. So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries.


1 Answers

Thanks nick rulez. I made an example of DBs listing:

$user = 'root';
$pass = 'root';
$server = 'localhost';

$dbh = new PDO( "mysql:host=$server", $user, $pass );
$dbs = $dbh->query( 'SHOW DATABASES' );

while( ( $db = $dbs->fetchColumn( 0 ) ) !== false )
{
    echo $db.'<br>';
}
like image 129
Falcon Avatar answered Sep 19 '22 03:09

Falcon