Question

This does not work with my PHP 5.3.3 installation on WAMP / Windows 7:

mysql_connect('localhost', 'root', '');

After Maximum execution time, this error is presented:

Warning: mysql_connect() [function.mysql-connect]: [2002] A connection attempt failed because the connected party did not (trying to connect via tcp://localhost:3306)

Warning: mysql_connect() [function.mysql-connect]: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

This works:

mysql_connect('127.0.0.1', 'root', '');

I'm wondering if it has something to do with this, from the PHP docs:

Whenever you specify "localhost" or "localhost:port" as server, the MySQL client library will override this and try to connect to a local socket (named pipe on Windows). If you want to use TCP/IP, use "127.0.0.1" instead of "localhost". If the MySQL client library tries to connect to the wrong local socket, you should set the correct path as in your PHP configuration and leave the server field blank.

This is from my php.ini:

; Default socket name for local MySQL connects.  If empty, uses the built-in
; MySQL defaults.
; http://php.net/mysql.default-socket
mysql.default_socket =

Is this a bug, or what is going on?


Update: I'm using MySQL 5.1.36 something, and I can connect to it otherwise. Forgot to mention, but this works with PHP 5.3.0 and 5.2.11. Ofcourse I can just change localhost to 127.0.0.1, but I want to know why I can't use localhost.


Update 2: Adding (uncommenting) 127.0.0.1 localhost to the hosts file made it work. But why is this necessary?

Was it helpful?

Solution 3

Filed a bug with PHP. The problem is with MySQL, and has to do with it not correctly connecting to all possible IP addresses for a domain.

Solution? Don't use host names to connect to databases, if it isn't absolutely necessary. This might also have a positive impact on performance.

OTHER TIPS

Try adding 127.0.0.1 localhost to C:\Windows\System32\drivers\etc\hosts?

Are you just having trouble connecting through PHP or can you not establish a connection to MySQL from the command line as well? If you cannot connect at all, verify the service is running and listening on port 3306.

You can also try to change localhost to: 127.0.0.1:3306

Or

$cfg['Servers'][$i]['host'] = 'localhost';

to

$cfg['Servers'][$i]['host'] = '127.0.0.1';

This is actually a bug in the php_mysql driver. See http://bugs.php.net/bug.php?id=48082

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top