mysql_connect警告,数据库主机问题

时间:2013-06-16 14:22:00

标签: php mysql database-connection localhost mysql-connect

我突然想到这个:

Warning: mysql_connect(): in C:\xampp\htdocs\login.php on line 12 cannot connect to server 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.

我使用此代码:

$dbhost="localhost";
$dbusername="dbusername";
$dbpassword="dbpassword";
$db_name="database";

mysql_connect("$dbhost", "$dbusername", "$dbpassword") or die("cannot connect to server". mysql_error()); 
mysql_select_db("$db_name") or die("cannot select db". mysql_error());

将主机更改为:

$dbhost="127.0.0.1";

一切都恢复正常。

为什么会这样?如何修复它像以前一样工作? 谢谢!

1 个答案:

答案 0 :(得分:0)

您使用的是Linux吗?然后它发生,因为插座。如果指定127.0.0.1 PHP使用TCP / IP通信。如果您键入localhost,它会尝试与套接字(mysql.sock)进行通信。 MySQL可能未配置为支持它们,或者您的系统阻止PHP访问套接字文件。

编辑:可能相关:mysql_connect (localhost / 127.0.0.1) slow on Windows platform