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

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

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

$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 新手。幼稚了……

转载于:https://my.oschina.net/guodapeng/blog/3016512

你可能感兴趣的:(MySQL mysqli_connect() 不能连接数据库问题)