Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot connect to MySQL through PHP

Seems like a beginner question but I can't seem to figure it out ...

I have a fresh Windows 7 x64 / Apache 2.2 / PHP 5.2 / MySQL 5 x64 installation.
Actually I tried both IIS and Apache.

But this PHP Code does not work:

<?
$hostname = "localhost";
$username = "xxx";
$password = "xxx";

$db = mysql_connect($hostname,$username,$password) or die("die");
?>
  • I can connect OK to the MySQL database using direct command line, using of course the same login/password.
  • I can access the MySQL database through the network with still the same login/password.
  • PHP is working otherwise (echo("hello world") does work).
  • The MySQL extension is enabled in php.ini. In fact, if I disable it I get Call to undefined function mysql_connect().
  • Windows Firewall disabled.
  • No error message. It just doesn't return anything. After 600 seconds, it times out:

        Fatal error: Maximum execution time of 60 seconds exceeded in
            C:\Ampache\try.php on line 6
    

Any clue?

like image 660
Jalil Avatar asked Dec 09 '09 01:12

Jalil


1 Answers

Wait Wait Wait ... I think I found it ...

RTM they said :-) It's all at http://php.net/manual/fr/function.mysql-connect.php :

Bruce Kirkpatrick - 28-Oct-2009 05:48 :
On Windows Vista or above, an entry in the Windows/System32/drivers/etc/hosts file causes mysql_connect() connections to "localhost" to timeout and never connect. This happens on php 5.3 and above since it now uses mysql native driver which has changed it connection behavior compared to libmysql.dll in previous versions. It is not a PHP bug, but definitely a configuration issue for users on new windows systems.

To get around this, you must remove the entry like this:
::1 localhost

and make sure you still have:
127.0.0.1 localhost

Also, you could change the code to connect to the ip instead, but that is inconvenient if you have many web sites.

This issue occurs on Windows Vista, Windows 7 and Windows Server 2008.

In fact it works with

$host = "127.0.0.1";

Thanks for your interest !

like image 138
Jalil Avatar answered Sep 20 '22 03:09

Jalil