PHP connection failed: SQLSTATE connection refused
P粉068510991
P粉068510991 2023-08-23 18:49:26
0
2
584
<p>I'm trying to connect to a MySQL database on phpmyadmin using a PHP connection. Nothing special about the connection, just wanted to see if the connection was successful. I'm using MAMP to host the database and the connection I'm trying to use is this: </p> <pre class="brush:php;toolbar:false;"><?php $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(); } ?></pre> <p>I've been using Postman to test that the connection is working, but I keep getting this error message: </p> <blockquote> <p>Connection failed: SQLSTATE[HY000] [2002] Connection refused</p> </blockquote> <p>Before I received the following error message: </p> <blockquote> <p>Connection failed: SQLSTATE[HY000] [2002] No such file or directory</p> </blockquote> <p>This is because I set the server name to localhost and by changing it to the IP address it causes the connection to be refused and I don't know what is going wrong. </p> <p>Any help regarding this issue would be greatly appreciated. </p>
P粉068510991
P粉068510991

reply all(2)
P粉434996845

I spend quite a bit of time in a docker environment where all my containers are docker containers and I use Phinx for migrations . Just to share the different responses for different configurations.

Working Solution

"host" => "db", // {docker container's name} Worked
"host" => "172.22.112.1", // {some docker IP through ipconfig - may change on every instance - usually something like 172.x.x.x} Worked

Invalid solution

"host" => "127.0.0.1", // SQLSTATE[HY000] [2002] Connection refused
"host" => "docker.host.internal", //  SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name does not resolve
"host" => "localhost", //  SQLSTATE[HY000] [2002] No such file or directory

I ran Phinx as follows.

docker compose --env-file .env run --rm phinx status -e development
P粉186017651

I found the reason why the connection wasn't working, it was because the connection was trying to connect to port 8888 when it needed to connect to port 8889.

$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);

This solved the problem, although changing the server name to localhost still gave the error.

Connection failed: SQLSTATE[HY000] [2002] No such file or directory

But when entering the IP address as the server name, it connects successfully.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template