问题描述
我有以下 php 文件:
I have the following php file:
<?php
function show_error($stage) {
echo "<p>MySql error: " . mysql_error() . '</p>';
echo "<p>ErrorCode: " . mysql_errno() . '</p>';
die($stage);
}
$link = mysql_connect('localhost', 'blog', 'sql-password');
if (!$link) {
show_error('connect');
}
mysql_select_db('blog') or show_error();
$result = mysql_query('select col1 from test_table');
if (!$result) {
show_error('query');
}
$col = mysql_result($result, 0);
echo "<p>Result is: [" . $col . "]</p>";
mysql_close($link);
?>
当我运行这个时,我得到错误:
When I run this, I get error:
MySql error: No such file or directory
ErrorCode: 2002
connect
但是,如果我改变行
$link = mysql_connect('localhost', 'blog', 'my-password');
到
$link = mysql_connect('127.0.0.1', 'blog', 'my-password');
一切正常.我该如何解决这个问题,以便它与 localhost
或 127.0.0.1
一起使用,以及为什么使用 localhost
与 127.0 的工作方式不同.0.1
?
it all works correctly. How can I fix this so that it works with either localhost
or 127.0.0.1
, and why does using localhost
work differently to 127.0.0.1
?
额外信息(一些谷歌回复表明这些很重要):
Extra info (some google responses indicated these were important):
- 行
127.0.0.1 localhost
出现在我的/etc/hosts
文件中,并且ping localhost
工作正常,并点击127.0.0.1
地址./etc/hosts
文件中没有其他行提到localhost
. - 我在 Mac OSX Snow Leopard 中运行它.
最后
stat/tmp/mysql.sock
命令的结果是:
- the line
127.0.0.1 localhost
appears in my/etc/hosts
file, andping localhost
works correctly, and hits the127.0.0.1
address. There are no other lines mentioninglocalhost
in the/etc/hosts
file. - I'm running it in Mac OSX Snow Leopard.
Finally, the result of the command
stat /tmp/mysql.sock
is:
234881044 28829652 srwxrwxrwx 1 _mysql 轮 0 0 "Jul 10 18:29:37 2011" "Jul 10 18:29:37 2011" "Jul 10 17:28:10213:10213:1011"" 4096 0 0/tmp/mysql.sock
234881044 28829652 srwxrwxrwx 1 _mysql wheel 0 0 "Jul 10 18:29:37 2011" "Jul 10 18:29:37 2011" "Jul 10 18:29:37 2011" "Jul 10 18:29:09 2011" 4096 0 0 /tmp/mysql.sock
推荐答案
MySQL 客户端神奇地知道 'localhost' 表示本地机器,因此它尝试连接到 Unix 套接字而不是发出网络请求——这是其实效率更高.这里的问题是您要么没有使用 Unix 套接字,要么——可能更有可能——MySQL 客户端库不知道在哪里可以找到 Unix 套接字文件.
The MySQL client magically knows that 'localhost' means the local machine, so it tries to connect to a Unix socket instead of making a network request--which is actually more efficient. The problem here is that you're either not using a Unix socket, or--probably more likely--the MySQL client libraries don't know where to find the Unix socket file.
我希望我能告诉您该配置的位置,但是 a) 我已经 3 年多没有积极使用 MySQL,并且 b) 我从未在 OSX 上使用过 MySQL.
I wish I could tell you where that configuration lives, but a) I haven't actively used MySQL in over 3 years, and b) I've never used MySQL on OSX.
这篇关于使用 php 连接到 mysql 时,仅在使用 localhost(而不是 127.0.0.1)时才会出现 mysql 2002 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!