Home >Backend Development >PHP Tutorial >Why Does My PHP Connection to MySQL Fail with \'Connection refused\' in MAMP?
PHP Connection Failure: "Connection refused"
When attempting to establish a PHP connection to a MySQL database hosted on phpMyAdmin using MAMP, users may encounter the error "Connection failed: SQLSTATE[HY000] [2002] Connection refused." This error typically occurs due to an incorrect hostname or port configuration in the connection string.
Initially, the error "SQLSTATE[HY000] [2002] No such file or directory" was encountered because the hostname was set to "localhost," which corresponds to port 8888 for MAMP installations. To rectify this issue, the hostname should be changed to the server's IP address (e.g., "127.0.0.1").
However, the "Connection refused" error persisted despite the hostname modification. The underlying cause was determined to be an incorrect port configuration. By default, MySQL on MAMP listens on port 8889 rather than the standard port 3306. Adjusting the port in the connection string to 8889 resolved the issue:
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
It's worth noting that using "localhost" as the hostname still resulted in the "No such file or directory" error. Therefore, it is recommended to use the server's IP address for the hostname to ensure a successful connection.
The above is the detailed content of Why Does My PHP Connection to MySQL Fail with \'Connection refused\' in MAMP?. For more information, please follow other related articles on the PHP Chinese website!