If you’re having problem connecting to your MySQL server within your PHP files and your PHP / MySQL / Apache are setup correctly, this post might solve your prblem.
Reproducing the problem:
When having a mysql_connect() statement within an executed PHP script – your browser will hang and after the php timeout (default is 60 seconds) pass this error will be displayed in your browser window:
PHP Warning: mysqli::mysqli(): [2002] A connection attempt failed because the connected party did not (trying to connect via tcp://localhost:3306) in xxx.php on line 2
PHP Warning: mysqli::mysqli(): (HY000/2002): 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.
in xxx.php on line 2
I have spent all morning trying to setup my webserver on this new PC with Windows Vista, it seems like whatever was changed – PHP couldn’t connect to MySQL.
After thinking what might cause this problem since I have been installing webservers for years and this never happened – I looked into the root cause of the problem which was found to be my OS, Windows Vista (Argh!).
(The following info has been copied from coreygilmore.com – finding out this solution took a really long time)
PHP bug #45150 suggests that this is due to issues resolving localhost on Windows. This is partially correct, more specifically it’s an issue with localhost resolving to ::1 when IPv6 is enabled.
While it feels like Windows has shoehorned in IPv6 support, the blame seems to lie with MySQL, which won’t support IPv6 until version 6.0.
I’m not sure why the timeout isn’t instant, the port is closed, so it could be partially a problem with PHP or Windows.
The Fix
Open up %windir%\system32\drivers\etc\hosts
with a text editor and comment out the line that looks like:
::1 localhost
Prefix it with a #, like so:
#::1 localhost
Save it and your PHP/MySQL connections will immediately begin working. You could also use 127.0.0.1 in your connection string instead of localhost, but I didn’t want to change code in innumerable files.
If you have problem saving the document (this could be because of administrator rights or read only) just move the file to another directory (your desktop) modify it and copy it back to your etc directory.
Hope this solution helped,
Resources :
New to PHP? start learning PHP with Robert Plank’s Easy PHP ebook.