Access the local MySQL database in PHP with the following code:
$mysqli = new mysqli("localhost", $name, $passwd, "test");if ($mysqli->connect_errno) { die("Failed to Connect to mysql: " . $mysqli->connect_errno);}$result = $mysqli->query("SELECT * FROM pet;");if(!$result){ echo "QUERY ERROR: " . $mysqli->error;}... ...$mysqli->close();
When the host name is written localhost
, the records in the library table can be displayed as normal. And when the host name is written 127.0.0.1
, although the connection database did not report error, but reported QUERY ERROR
. Is that localhost
so 127.0.0.1
different? What's going on here?
Reply content:
Access the local MySQL database in PHP with the following code:
$mysqli = new mysqli("localhost", $name, $passwd, "test");if ($mysqli->connect_errno) { die("Failed to Connect to mysql: " . $mysqli->connect_errno);}$result = $mysqli->query("SELECT * FROM pet;");if(!$result){ echo "QUERY ERROR: " . $mysqli->error;}... ...$mysqli->close();
When the host name is written localhost
, the records in the library table can be displayed as normal. And when the host name is written 127.0.0.1
, although the connection database did not report error, but reported QUERY ERROR
. Is that localhost
so 127.0.0.1
different? What's going on here?
Loaclhost and 127.0.0.1 are not equivalent.
Loaclhost is a name, this name generally represents the 127.0.0.1 IP address , that is, when you say to the computer, I want to go to Loaclhost, The computer translates it into 127.0.0.1 via DNS or NBNS or the hosts file.
If you use Loaclhost to link to a database, MySQL uses Unixsocket to link to it. If 127.0.0.1 is specified, TCP/IP is used to link.
So try to use 127.0.0.1.
Well, see the answer has been adopted, but still have to say a little more
In fact, the answer is not very rigorous, but since it was adopted, say a little more. localhost
in general, and 127.0.0.1
is equivalent, but MySQL in the problem of dealing with this noun there are some differences, is based on different addresses to take different means of communication.
The reason, I guess, is that the local application can get better performance. And localhost
this address does not match in MySQL. That user@'%'
cannot be matched touser@'localhost'