PHP connection failed: SQLSTATE connection refused
P粉068510991
2023-08-23 18:49:26
<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>
I spend quite a bit of time in a
docker
environment where all my containers aredocker
containers and I usePhinx
for migrations . Just to share the different responses for different configurations.Working Solution
Invalid solution
I ran
Phinx
as follows.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.
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.