php - 无法使用 127.0.0.1 连接到 mysql

标签 php mysql database

通过以下代码,我可以连接到 mysql: mysql_connect("localhost","username","");

但如果我将 localhost 更改为 127.0.0.1 我会收到以下错误:

无法连接到“127.0.0.1”上的 MySQL 服务器 (13)

为什么它不适用于 127.0.0.1?

最佳答案

localhost 是特殊情况,使用 UNIX 套接字而不是 TCP/IP。 127.0.0.1 没有得到那种特殊处理。

参见 the documentation :

On Unix, MySQL programs treat the host name localhost specially, in a way that is likely different from what you expect compared to other network-based programs. For connections to localhost, MySQL programs attempt to connect to the local server by using a Unix socket file. This occurs even if a --port or -P option is given to specify a port number. To ensure that the client makes a TCP/IP connection to the local server, use --host or -h to specify a host name value of 127.0.0.1, or the IP address or name of the local server. You can also specify the connection protocol explicitly, even for localhost, by using the --protocol=TCP option.

如果在您使用 TCP/IP 时它不起作用,那么数据库可能没有在网络上监听。这通常是一件好事,因为它增强了安全性(并不是说监听 127.0.0.1 会暴露任何问题,而是监听所有接口(interface)会提供更多攻击机会)。

如果您真的想允许通过网络连接,请参阅 skip-networking .

关于php - 无法使用 127.0.0.1 连接到 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10347993/

相关文章:

php - 在索引中包含标题?

php - 如何保护我的网站

database - 用于无向图的Nosql DB?

php - 使用 PHP 将输入 SQL 查询格式化为 HTML?

mysql - 这里使用什么类型的连接?

mysql - 从表中选择 * 总是错过第一行结果

PHP 代码没有从数据库中获取正确的值

PHP mysql_num_rows() 期望参数1为resource

php - Symfony2 数据库配置

mysql - 类未找到异常 : Cycle detected while trying to load class - at Entity Classes (When starting JPA bundle in Karaf)