PHP Connectivity Issue: "Connection failed: SQLSTATE[HY000] [2002] Connection refused"
Problem:
When attempting to establish a PHP connection to a MySQL database hosted on phpMyAdmin, users may receive the error message "Connection failed: SQLSTATE[HY000] [2002] Connection refused."
Analysis:
Initially, the connection attempted to connect using "localhost" as the "servername," but this resulted in the error "Connection failed: SQLSTATE[HY000] [2002] No such file or directory." Changing the "servername" to the IP address of the database host eliminated the file or directory error, but triggered the "Connection refused" error.
Solution:
Further investigation revealed that the connection was attempting to connect to Port 8888, whereas the correct port for MAMP to host the database was 8889. Modifying the connection string to include the correct port resolved the issue:
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
Additional Note:
While changing the "servername" to "localhost" continued to result in the "No such file or directory" error, connecting with the database's IP address for the "servername" remained successful.
The above is the detailed content of Why Does My PHP Connection to MySQL Fail with 'Connection refused' and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!