MySQL mysqli_connect() 不能连接数据库问题

原创
2019/03/01 10:13
阅读数 1.7K

事情是这样的。 这样的代码能行:

$servername = "localhost";
$username = "username";
$password = "password";

// 创建连接
$conn = new mysqli($servername, $username, $password);

// 检测连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}
echo "连接成功";

这样的代码能行:

$servername = "localhost";
$username = "username";
$password = "password";

$link = mysqli_connect($servername, $username, $password, 'wxjs');

if (!$link) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;

mysqli_close($link);

输出:

Success: A proper connection to MySQL was made! The my_db database is great.
Host information: Localhost via UNIX socket

这样的代码不行:

$servername = "127.0.0.1";
$username = "username";
$password = "password";

$link = mysqli_connect($servername, $username, $password, 'wxjs');

if (!$link) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;

mysqli_close($link);

输出:

Error: Unable to connect to MySQL.
Debugging errno: 2002
Debugging error: Permission denied

得出结论:用IP和用localhost是不一样的。

我还找到了一个很变态的方法解决 用 IP 不行的,居然是关掉防火墙……

$ sudo setenforce 0

MySQL 新手。幼稚了……

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部