How can I get a list of MySQL databases in PHP using PDO?
I wonder how can I get the list of MySQL databases in PHP using PDO wi开发者_开发百科thout 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.
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>';
}
You can use
show databases
or a query on the information_schema:
select schema_name from information_schema.schemata
try{
$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 />";
}
精彩评论