0

So I have a PDO Connection set up in PHP and I can access the database I am trying to connect to within navicat, but can't code wise. Should mention that the database is within vagrant alongside the code itself.

If I use localhost in the servername then I get file not found within the connection and with 127.0.0.1, I receive the error of connection refused so am not too sure what is causing the issue, because most people said it was the port which I have declared too.

The PDO Connection

$servername = "127.0.0.1";
$username = "root";
$password = "secret";

try {
  $conn = new PDO("mysql:host=$servername;port=3306;dbname=staff_members", $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();
 }
Phil
  • 157,677
  • 23
  • 242
  • 245
  • 1
    For the mysql driver `localhost` will try to use the Unix socket [TLDR: a file], and `127.0.0.1` actually tries a TCP connection. If both of these fail either your mysql server is not running, or it's not listening on either of those local interfaces. – Sammitch Mar 17 '22 at 23:12
  • @Sammitch So considering I can access the actual database within navicat means it's not listening I'm assuming? How would I go about checking this? –  Mar 17 '22 at 23:17
  • What are the connection details you're using in Navicat? – Phil Mar 17 '22 at 23:28
  • 1
    Connection refused means there is **no mysql service running** on the **address you are connecting to**. – Your Common Sense Mar 18 '22 at 04:06

0 Answers0