PHP Connection Refusal with SQLSTATE[HY000] [2002]
When attempting to establish a database connection in PHP, encountering the error "SQLSTATE[HY000] [2002] Connection refused" indicates that the connection attempt failed due to network communication issues. This can be resolved by addressing the following aspects:
Incorrect Port Configuration:
The code provided set the hostname as "127.0.0.1" but did not specify the port explicitly. When using MAMP, it's common for MySQL to run on port 8889 instead of the default 3306. To resolve this, modify the connection code to include the correct port:
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
Firewall or Network Restrictions:
Ensure that firewall settings or network configurations are not blocking access to the database server. Verify that port 8889 is allowed for incoming connections on the server.
Correct Hostname Configuration:
Using "127.0.0.1" for the hostname in MAMP should work, but if it still gives the "No such file or directory" error, try using "localhost" instead. This issue may be related to specific server configurations.
The above is the detailed content of Why is my PHP code returning \'SQLSTATE[HY000] [2002] Connection refused\' when connecting to my MySQL database?. For more information, please follow other related articles on the PHP Chinese website!