简体   繁体   中英

MySQL Error mysqli::__construct(): (HY000/2002): Connection refused

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.

First of all, using localhost as a domain name isnot 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM