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.
You can use
show databases
or a query on the information_schema:
select schema_name from information_schema.schemata
USE command to switch to your database of choice. Also @nick, +1 for information_schematry{
$DBH = new PDO("mysql:host=localhost", "root", "");
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e) {
echo "Fail";
}
$rs = $dbo->query("SHOW DATABASES");
while ($h = $rs->fetch(PDO::FETCH_NUM)) {
echo $r[0]."<br>";
}
Another method similar to Falcon's:
This script uses foreach instead of while and print instead of echo for the db names and the break tag is set up as it would be used with XML. It also uses the associative property, the column name, instead of the array index of the column in the returned row to display the desired result.
This assumes you have the PDO connection properly set up and = $dbconn. Many times $db is used instead of $dbconn in examples.
$stmt ="SHOW DATABASES";
foreach($dbconn->query($stmt) as $row){
print $row['Database'];echo"<br />";
}
show databaseslike @nick rulez mentioned; however you will still need to at least log in to the database server and create the connection.