Home > Database > Mysql Tutorial > How to Fix 'Connection failed: SQLSTATE[HY000] [2002] Connection refused' in PHP MySQL Connections?

How to Fix 'Connection failed: SQLSTATE[HY000] [2002] Connection refused' in PHP MySQL Connections?

DDD
Release: 2024-12-11 09:41:11
Original
523 people have browsed it

How to Fix

Resolving "Connection failed: SQLSTATE[HY000] [2002] Connection refused" with PHP

When attempting to establish a PHP connection to a MySQL database hosted on phpMyAdmin, users may encounter the frustrating error "Connection failed: SQLSTATE[HY000] [2002] Connection refused." This error indicates that the PHP script cannot connect to the database server.

For instance, consider the following PHP code:

$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();
}
Copy after login

This code attempts to connect to a MySQL database using the PDO (PHP Data Objects) object. However, when using the connection through Postman, the error "Connection failed: SQLSTATE[HY000] [2002] Connection refused" occurs.

Initially, one might encounter the error "Connection failed: SQLSTATE[HY000] [2002] No such file or directory." This occurs when the servername is set to "localhost." Changing the servername to the IP address addresses this issue but results in the "Connection refused" error.

The solution to this connection refusal lies in the port number being used. The default port for MySQL is 3306. However, for connections via MAMP, the port should be set to 8889.

Adjusting the code as follows will resolve the connection issue:

$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password); 
Copy after login

With this modification, the PHP script will successfully connect to the MySQL database using port 8889.

The above is the detailed content of How to Fix 'Connection failed: SQLSTATE[HY000] [2002] Connection refused' in PHP MySQL Connections?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template