Connecting to mysql

hello every one, i installed lamp. but when i try to connect to mysql with php this error happens. ERROR: Could not connect. SQLSTATE[HY000] [2002] Connection refused.
can you help ???

Hi @Mohammad.Shabani, and welcome!

That seems a lot like the first time I tried to do it and this error could be because of a lot of reasons.

Have you done any specific configuration for MySQL? I’m guessing not.
Are you trying to connect to MySQL on the same machine as where PHP is? I’m guessing so. (That is the most common way to do it, after all.)

What is the connection string you’re using to try to connect?

both of your guesses are right,
and this is my code:
$pdo = new PDO("mysql:host=127.0.0.1;dbname=$dbname", $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

The error means that there is no listener running on this port. The command to the PDO constructor asks for the default port, which is TCP 3306. Go look for the port list. It should show you mariadb listening on port 3306, something like:

$ sudo ss -tulpn | grep :3306
tcp   LISTEN 0      54                                0.0.0.0:3306       0.0.0.0:*    users:(("mariadbd",pid=585,fd=19))

If there is no such line, then MySQL or MariaDB is not running and you need to go one step back. If there is such line, then check the IP address (maybe it’s 127.0.1.1 instead of 127.0.0.1 or the LAN ip address or whatever. The IP address 0.0.0.0 as in the example is always ok).

1 Like

when i checked the port list there was no listener on 3306. but when i run
$ systemctl status mysqld
,it shows that mysql is running. should i reinstall mysql??

Then I’m personally getting the idea that MySQL/Mariadb isn’t running on the standard port of 3306.

I suggest looking in the configuration files somewhere for it, or a reinstall might fix it. But also, it might not, I don’t know which. It probably depends on if the configuration files get replaced, or not.

As you can see from my example output above, running the command ss -tulpn as root (or sudo) will also give you the process name.

So, there should be a listener listed whose process name is either mariadb or mysql, just grep for it.