我正在尝试使用 PHP 连接到 mysql 数据库。我在 pho 文件中的代码是:
try {
$pdo = new PDO("mysql:host=localhost;dbname=BurgerBar",
"root", "root");
} catch (PDOException $e) {
$response = "Failed to connect: ";
$response .= $e->getMessage();
die($response);
}
当我在浏览器中运行代码时,我得到
Failed to connect: SQLSTATE[42000] [1049] Unknown database 'burgerbar'
但是,当我在终端中输入 mysql 时,使用密码 root 以 root 身份登录并运行
show databases;
我明白了
+--------------------+
| Database |
+--------------------+
| information_schema |
| BurgerBar |
| mysql |
| performance_schema |
| test |
+--------------------+
所以它表明它存在于mysql中。我正在使用 MAMP,但无法弄清楚这一点。
最佳答案
您需要将连接字符串从 localhost 更改为 MAMP 使用的 IP(而不是 localhost),并添加 MAMP 与 mysql 通信的端口。试试这个:
$pdo = new PDO("mysql:host=127.0.0.1;port=5432;dbname=BurgerBar"
关于php - 使用 PHP 和 MySQL 连接到现有数据库时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26431693/