如何使用 PDO 在 localhost 中获取数据库数组

尝试使用 PDO 在 localhost 中获取数据库数组


$user = 'root';

$server = 'localhost';

$db = new PDO("mysql:host=$server", $user);


$sql = "show databases";

$st = $db->prepare($sql);

$st->execute();

$arr = $st->fetchAll(PDO::FETCH_ASSOC);

foreach($arr as $el){

    echo $el . '<br>'; // error - array to string conversion

}

也试过:


 $arr = $st->fetch(PDO::FETCH_ASSOC);

结果 - 仅回显第一个数据库


有什么帮助吗?


慕斯王
浏览 115回答 2
2回答

LEATH

从信息架构中获取信息,例如:SELECT `SCHEMA_NAME` FROM `information_schema`.`SCHEMATA`;还有更多关于数据库(模式)的信息样本MariaDB [(none)]> SELECT `SCHEMA_NAME` FROM `information_schema`.`SCHEMATA`;+--------------------+| SCHEMA_NAME&nbsp; &nbsp; &nbsp; &nbsp; |+--------------------+| bernd&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; || information_schema || mysql&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; || performance_schema |+--------------------+4 rows in set (0.00 sec)MariaDB [(none)]>

慕桂英4014372

只需遍历结果并打印它:while ($arr = $stmt->fetch(PDO::FETCH_ASSOC)){&nbsp; &nbsp; print_r($arr);}结果是您的本地主机中的数据库名称。例如:Array(&nbsp; &nbsp; [Database] => mysql)Array(&nbsp; &nbsp; [Database] => performance_schema)Array(&nbsp; &nbsp; [Database] => phpmyadmin)编辑:$databases = [];while ($arr = $stmt->fetch(PDO::FETCH_ASSOC)){&nbsp; &nbsp; $databases[] = $arr["Database"];}
打开App,查看更多内容
随时随地看视频慕课网APP