0

I'm trying to run a PHP Script that contains a MySQL connection, when I run the command I get the following error in the terminal:

'Warning: mysqli::__construct(): (HY000/2002): Connection refused'

Even with PDO, I get the error:

'Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] No such file or directory in ...'

I'm running the script on Mac OS X, and I have MAMP as APACHE/MySQL local server.

The command that I use for running the script is:

'php main.php'

and the content of the 'main.php' file with PDO is:

$db = new PDO('mysql:host=localhost;dbname=test',root,root);

with mysqli connector:

$db = new mysqli("localhost", "test", "root", "root");

I tried with '127.0.0.1' instead of 'localhost' and I get the same errors in both cases.

LMC
  • 10,453
  • 2
  • 27
  • 52

1 Answers1

-1

First of all, using localhost as a domain name is not supported in PHP. It will not be resolved as 127.0.0.1.

Second, even using 127.0.0.1 might not work in servers with multiple interfaces or with special routing rules. Run mysqlcheck --help and take the IP address shown at the bottom in the "host" field. For example:

port                              3306
host                              192.168.1.23

Use the IP and port that MySQL recognizes:

$db = new mysqli("192.168.1.23:3306", "test", "root", "root");
Victor
  • 460
  • 3
  • 11
  • Can you share more details about that statement "It will not be resolved"? I think the documentation is inconsistent, as https://www.php.net/manual/en/pdo.connections.php uses `localhost`, https://www.w3schools.com/php/php_mysql_connect.asp does that too – Nico Haase Feb 28 '20 at 09:02
  • ...additionally, the link you've provided shows successfully started MySQL connections both for `localhost` and `127.0.0.1` – Nico Haase Feb 28 '20 at 09:03
  • As I posted in the link "not supported in PHP" (https://www.php.net/manual/en/mysqli.quickstart.connections.php), the PHP documentation itself mentions explicitly (second paragraph): "The hostname localhost has a special meaning. It is bound to the use of Unix domain sockets. It is not possible to open a TCP/IP connection using the hostname localhost you must use 127.0.0.1 instead. " – Victor Mar 02 '20 at 01:51
  • Yeah, as written there: "it is not possible to open a **TCP/IP connection**" - using sockets, this works fine. Additionally, using sockets is faster as you skip the network overhead (see https://stackoverflow.com/q/1838358 for this) – Nico Haase Mar 02 '20 at 07:45