PHP 连接失败:SQLSTATE[HY000] [2002] 连接被拒绝 [英] PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused
问题描述
我正在尝试使用 PHP 连接来连接 phpmyadmin 上的 MySQL 数据库.连接没有什么特别的,只是想看看连接是否成功.我使用 MAMP 来托管数据库,我尝试使用的连接是这样的:
I am trying to use a PHP connection to connect MySQL Database which is on phpmyadmin. Nothing fancy about the connection just trying to see whether the connection is successful or not. I am using MAMP to host the database, the connection I am trying to use is this:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;dbname=AppDatabase", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
我一直在使用邮递员来测试连接是否正常工作,但我一直收到此错误消息:
I have been using postman to test to see if the connection is working, but I keep receiving this error message:
连接失败:SQLSTATE[HY000] [2002] 连接被拒绝
Connection failed: SQLSTATE[HY000] [2002] Connection refused
在我收到以下错误消息之前:
Before I was receiving an error message of:
连接失败:SQLSTATE[HY000] [2002] 没有那个文件或目录
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
这是因为我已将服务器名称设置为 localhost,通过将其更改为 IP 地址,它拒绝了我的连接,我不知道出了什么问题.
This was because I had set the servername to localhost, through changing this to the IP address it has given me connection refused and I have no idea what is wrong.
对此的任何帮助将不胜感激.
Any help regarding this would be appreciated.
推荐答案
我找到了连接不工作的原因,是因为连接试图连接到端口 8888,而它需要连接到端口 8889.
I found the reason why the connection was not working, it was because the connection was trying to connect to port 8888, when it needed to connect to port 8889.
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
这解决了问题,尽管将服务器名称更改为 localhost 仍然会出现错误.
This fixed the problem, although changing the server name to localhost still gives the error.
连接失败:SQLSTATE[HY000] [2002] 没有那个文件或目录
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
但是当服务器名称输入IP地址时它连接成功.
But it connects successfully when the IP address is entered for the server name.
这篇关于PHP 连接失败:SQLSTATE[HY000] [2002] 连接被拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!