- PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused
- How to Handle PDOException in PHP
- What Causes PDOException
- PDOException Example
- How to Handle PDOException
- Track, Analyze and Manage Errors With Rollbar
- PHP PDO : SQLSTATE[HY000] [2002] Connection refused
- Solution
- PHP application cannot connect to MySQL over SSL
- Symptoms
- Cause
- Solution
PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused
The error message «SQLSTATE[HY000] [2002] Connection refused» typically indicates that the client was unable to establish a connection to the database server. This can be due to several reasons, such as:
- The database server is not running.
- The database server is not running on the correct host or port.
- There is a firewall blocking access to the database server.
- The credentials (username and password) used to connect to the database are incorrect.
To troubleshoot the problem, you should check the following:
- Verify that the database server is running.
- Check that the database server is running on the correct host and port. You can do this by checking the configuration of your database client (e.g., in a configuration file or your code).
- Check for any firewall rules that may be blocking access to the database.
- Verify that the credentials used to connect to the database are correct. Ensure the username and password are correct, and the user has the necessary permissions to access the database.
If you still have problems after checking these items, there may be a problem with the database server itself or the network connection between the server and the client. In this case, you may need to contact the system administrator or the database administrator for further assistance.
How to Handle PDOException in PHP
The PHP PDOException is a runtime exception that occurs when something goes wrong while using the PDO (PHP Data Objects) class or its related extensions. For example, this exception can occur while handling database connections or queries.
What Causes PDOException
PHP Data Objects (PDO) are a collection of APIs that are used to access and work with databases. The PDOException is thrown anytime an issue occurs while using the PDO interface. Common situations where this exception can occur are:
- Attempting to connect to a database e.g. entering an incorrect password for the database connection.
- Issuing an SQL statement e.g. missing database table, invalid SQL statement.
PDOException Example
Here’s an example of a PHP PDOException thrown when facing issues connecting to a database using the PDO interface:
?php $dbh = new PDO("mysql:host=localhost;dbname=test", "user", "pass"); ?>
In the above example, the PDO class is used to establish a connection to a database. Since the database connection parameters are incorrect, running the above code throws a PDOException :
PHP Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] Connection refused in main.php:2 Stack trace: #0 main.php(2): PDO->__construct('mysql:host=loca. ', 'user', 'pass') #1 thrown in main.php on line 2
How to Handle PDOException
The PDOException can be caught and handled using a try-catch block. The try block should contain the lines of code that can throw the exception and the catch block should catch and handle the PDOException appropriately. The message associated with the exception can be retrieved using the Exception::getMessage method on the PDOException object.
Using the above approach, the previous example can be updated to handle the error:
?php try < $dbh = new PDO("mysql:host=localhost;dbname=test", "user", "pass"); >catch (PDOException $e) < print "Error: " . $e->getMessage(); > ?>
Here, a check is performed for the PDOException using the try-catch block. When the above code is executed, the catch block catches the PDOException and handles it, producing the following output:
Error: SQLSTATE[HY000] [2002] Connection refused
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing PHP errors easier than ever. Try it today!
PHP PDO : SQLSTATE[HY000] [2002] Connection refused
I cannot connect to my Database. First here is my PHP Script:
catch (PDOException $pdoE) < echo 'An Error occurred: ' . $pdoE->getMessage(); > ?>
A phpinfo() tells me that PDO Drivers are loaded as follows:
An Error occurred: SQLSTATE[HY000] [2002] Connection refused
I can connect to the same Database via Phpstorm with the same Password and Username.
Solution
It seems that this is not a problem related to the PHP Configuration.
The error Connection refused shows, from my point of view, that you can’t establish a connection from the php container to the mysql container.
You need to expose the 3306 Port to the Webserver Container so that the PHP Container can establish a connection to the database. If you already bridged the containers you need to use the containers IP address and not your loopback 127.0.0.1.
Please see this answer for more information how to connect both containers and how to make a connection from a php to a mysql container:
https://stackoverflow.com/a/43128428/1118905
To narrow down the problem, you can try to establish a connection from within the PHP Container via Netcat to your given DB Host.
For example you can try to establish a connection with the following commands:
- Get into the container from which you want to test the connection.
docker exec -it bash - Test to open up a connection via netcat (If not all ready available install it via f.e. apt)
nc -vz 127.0.0.1:3306
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0
PHP application cannot connect to MySQL over SSL
This article describes how to solve PDOException: SQLSTATE[HY000] [2002] Connection refused when connecting from any PHP application with PDO::MySQL to a SSL enabled MySQL database with mismatching CN.
Symptoms
Connecting to the database without SSL works, but when it is enabled, then you cannot connect although all certificates and keys are provided.
Database connection properties (in Drupal8) looks like:
array ( 'database' => 'database', 'username' => 'username', 'password' => 'password', 'prefix' => '', 'host' => 'hostname', 'port' => '3306', 'driver' => 'mysql', 'pdo' => [ \PDO::MYSQL_ATTR_SSL_KEY =>'/var/www/site/keys/client-key.pem', \PDO::MYSQL_ATTR_SSL_CERT =>'/var/www/site/keys/client-cert.pem', \PDO::MYSQL_ATTR_SSL_CA =>'/var/www/site/keys/server-ca.pem' ] )
When trying to connect older versions of PHP does not report the real error but just PDOException: SQLSTATE[HY000] [2002] Connection refused
while newer ones report an additional
PHP Fatal error: Uncaught PDOException: PDO::__construct(): Peer certificate CN=`*********:stage-database' did not match expected CN=`***.***.***.***'
and is reproducible with SSL enabled Google Cloud SQL instance because the issued certificates CN is not a resolvable FQDN which can be used to be connect to from outside.
Cause
The root cause is PHP by default verifies if the canonical name of the certificate matches the hostname you are trying to connect to. If that fails then connection is denied but this is not reported as an error or warning.
Solution
After a few bug reports and complaints a new PDO::MySQL attribute was added in php-7.0.18, php-7.1.4 with commit 247ce052cd0fc7d0d8ea1a0e7ea2075e9601766a but not documented in the official documentation. That parameter disables hostname verification and applications connect without any issue. I’ve commented on php.net about that here.
So add to your pdo properties array the following key – PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT
'pdo' => [ \PDO::MYSQL_ATTR_SSL_KEY =>'/var/www/site/keys/client-key.pem', \PDO::MYSQL_ATTR_SSL_CERT =>'/var/www/site/keys/client-cert.pem', \PDO::MYSQL_ATTR_SSL_CA =>'/var/www/site/keys/server-ca.pem', \PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT => false ]
If after adding this parameter you get an error message
PHP message: Error: Undefined class constant 'MYSQL_ATTR_SSL_VERIFY_SERVER_CERT'
then your PHP version does not support that parameter and you need to upgrade.
The solutions is applicable to any PHP application that uses PDO::MySQL. So far verified on Symfony, Laravel, Drupal