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(); }
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);
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!