Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (6.1k points)

I was trying to use a PHP connection to connect MySQL Database which was on PHPMyAdmin. Nothing fancy about the connection just trying to see whether the connection was successful or not. I was using MAMP to host the database, the connection I was trying to use is this:

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

I had been using postman to test to see if the connection was working, but I kept receiving this error message: 

Connection failed: SQLSTATE[HY000] [2002] Connection refused

Before I was receiving an error message of: 

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

 This was because I had set the servername to localhost, through changing this to the IP address it had given me the connection refused and I have no idea what is wrong.

Any help regarding this would be appreciated.

1 Answer

0 votes
by (12.7k points)

The connection was not working, 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 will fix the problem, although changing the server name to localhost still gives the error.

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

But it connects successfully when the IP address is entered for the server name.

If you want to learn more about SQL, Check out this SQL Certification by Intellipaat.

For more information visit :

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
...