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.
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.
To select data from a table using PDO, you can use: The query() method of a PDO object. Or a prepared statement.
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.
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>';
}
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