Unable to connect to MySQL from localhost: Strange error

If you trying to access your local MySQL database from your PHP script running on your local web server (like Apache) and encounter an error like below:

Warning: mysql_connect() [function.mysql-connect]: [2002] A connection attempt failed because the connected party did not (trying to connect via tcp://localhost:3306) in D:\projects\Pinlocal\public\test.php on line 12

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. in D:\projects\Pinlocal\public\test.php on line 12

Chances are that your MySQL database has been blocked by a firewall. However in my case my Firewall (McAfee Firewall) was configured to allow MySQL connections. I researched on net and all seem to point to configuring Firewall to allow MySQL. After about an hour of research I was stuck on the same problem and apparently the problem was something different since MySQL was already in my firewall exception list.

Few days back my McAfee alerted me that my Apache ┬áServer is attempting to make a connection and I instructed it to block the connection. I opened the Firewall console and found that my local Apache Web server has been blocked from making any type of connection. I unblocked my Apache executable and allowed it to make Outgoing connections and to my delight I am now able to connect to MySQL from my php script without any problems. Clearly my McAfee firewall was not allowing Apache to make a connection to MySQL and the above error message was somewhat misleading. I documented it here so may be it would help someone out there facing the same problem, as I am sure uninstalling and installing MySQL wasn’t going to solve the problem which I was thinking to do as last resort.