Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mysql

pdo

I am trying to use a PHP connection to connect MySQL Database which is on phpmyadmin. Nothing fancy about the connection just trying to see whether the connection is successful or not. I am using MAMP to host the database, the connection I am 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 have been using postman to test to see if the connection is working, but I keep 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 has given me connection refused and I have no idea what is wrong.

Any help regarding this would be appreciated.

like image 408
Jonck Avatar asked Apr 01 '15 15:04

Jonck


People also ask

Can't connect to the database server Sqlstate HY000 2002 Connection Refused?

Incorrect database settings Similarly, a major reason for sqlstate hy000 2002 error is the incorrect database settings in the configuration file. For the proper working of the program, the file should contain correct database server name, database user details and password. If the MySQL service is listening on 127.0.

What does Sqlstate HY000 2002 Connection refused mean?

The error (2002) Can't connect to ... normally means that there is no MySQL server running on the system or that you are using an incorrect Unix socket file name or TCP/IP port number when trying to connect to the server.

How do I fix Sqlstate HY000?

$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. But it connects successfully when the IP address is entered for the server name.


1 Answers

I found the reason why the connection was not 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 fixed 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.

like image 57
Jonck Avatar answered Sep 30 '22 20:09

Jonck