PHP: Resolving "Connection failed: SQLSTATE[HY000] [2002] Connection refused" Error
When connecting to MySQL using PHP via phpMyAdmin, you may encounter the "Connection failed: SQLSTATE[HY000] [2002] Connection refused" error. This indicates that the attempt to connect to the database was unsuccessful.
The original connection attempt used the server name "localhost," which was leading to the error "Connection failed: SQLSTATE[HY000] [2002] No such file or directory." Changing the server name to the IP address, as suggested in the question, resolved this issue.
However, even after changing the server name to the IP address, the "Connection failed" error continued to occur. The reason for this was that the connection was attempting to connect to port 8888, when it should have been connecting to port 8889.
To rectify this, the connection code was modified to the following:
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
This change fixed the problem, and the connection to the MySQL database was established successfully. However, it's worth noting that using "localhost" as the server name still resulted in the "Connection failed: SQLSTATE[HY000] [2002] No such file or directory" error, indicating that the IP address must be used for a successful connection.
The above is the detailed content of Why Does My PHP MySQL Connection Fail with \'Connection refused\' (SQLSTATE[HY000] [2002])?. For more information, please follow other related articles on the PHP Chinese website!