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
However, if I change the line
$link = mysql_connect('localhost', 'blog', 'my-password');
to
$link = mysql_connect('127.0.0.1', 'blog', 'my-password');
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
appears in my /etc/hosts
file, and ping localhost
works correctly, and hits the 127.0.0.1
address. There are no other lines mentioning localhost
in the /etc/hosts
file. Finally, the result of the command stat /tmp/mysql.sock
is:
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
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.