Home >Database >Mysql Tutorial >Why is My PHP MySQL Connection Refusing: Troubleshooting 'SQLSTATE[HY000] [2002] Connection Refused'?
Troubleshooting "Connection Failed: SQLSTATE[HY000] [2002] Connection Refused" Error
When encountering the error "Connection failed: SQLSTATE[HY000] [2002] Connection refused" during PHP MySQL database connection, there are several factors to investigate.
In the given scenario, the issue was related to the incorrect port number used for the connection. The initial configuration utilized "localhost" as the servername, which resolved to port 8888 on MAMP. However, the database was listening on port 8889. By modifying the code to explicitly specify port 8889, the connection was established successfully:
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
It's important to note that using "localhost" as the servername may still result in the "No such file or directory" error if the MySQL socket is not properly configured on the system. In such cases, using the explicit IP address of the host machine is recommended.
Therefore, the following modifications ensure a successful connection without encountering the "Connection refused" or "No such file or directory" errors:
$servername = "127.0.0.1"; $port = "8889"; ... $conn = new PDO("mysql:host=$servername;port=$port;dbname=AppDatabase", $username, $password);
The above is the detailed content of Why is My PHP MySQL Connection Refusing: Troubleshooting 'SQLSTATE[HY000] [2002] Connection Refused'?. For more information, please follow other related articles on the PHP Chinese website!