本文介绍了PHP连接失败:SQLSTATE [HY000] [2002]连接被拒绝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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:

在我收到以下错误消息之前:

Before I was receiving an error message of:

这是因为我已将服务器名设置为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]连接被拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 11:37