简体   繁体   English

如何使用PDO获取PHP中的MySQL数据库列表?

[英]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 without having to connect to a database first ( I mean no dbname in dsn )? 我想知道如何使用PDO在PHP中获得MySQL数据库列表,而不必先连接到数据库(我的意思是dsn中没有dbname)?

Usually I used to use the function mysql_list_dbs() but I no longer use mysql this way. 通常我以前使用函数mysql_list_dbs(),但不再使用mysql。

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: 或对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: 类似于Falcon的另一种方法:

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. 该脚本使用foreach代替while,并使用print代替echo来表示数据库名称,并且设置了break标签,因为它将与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. 假设您已经正确设置了PDO连接,并且= $ dbconn。 Many times $db is used instead of $dbconn in examples. 在示例中,很多时候使用$ db代替$ dbconn。

$stmt ="SHOW DATABASES";
foreach($dbconn->query($stmt) as $row){
print $row['Database'];echo"<br />";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM