连接失败:用户 ''username'@'localhost' 访问被拒绝(使用密码:YES)

2021-12-25 00:00:00 php mysqli

我正在尝试连接到服务器上的 MySQL,但出现以下错误.用户已创建并被授予所有权限.

I am trying to connect to MySQL on the server but gives following error. User is created and granted all privileges.

它可以在本地机器上运行,但在部署到服务器之后就不行了.

还有 mysql_connect 函数可以工作,但是 new mysqli() 给出如下所述的拒绝访问.

Also mysql_connect function works but new mysqli() gives access denied as mentioned below.

也尝试添加端口.

警告: mysqli::mysqli(): (HY000/1045): Access denied for user ''usernam'@'localhost' (using password: YES) in/home/domainname/public_html/autopublish/test.php on8号线连接失败:用户 ''username'@'localhost' 访问被拒绝(使用密码:YES)

Warning: mysqli::mysqli(): (HY000/1045): Access denied for user ''usernam'@'localhost' (using password: YES) in /home/domainname/public_html/autopublish/test.php on line 8 Connection failed: Access denied for user ''username'@'localhost' (using password: YES)

<?php
    $servername = "localhost";
    $username = "'xxxxx";
    $password = "xxxxx";
    $dbname = "xxxxx";

    // Create connection
    $conn = new mysqli($servername, $username, $password);  **//line 8**
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } else {
        echo "no connection";
    }

    $sql = "SELECT * FROM pages";
    $result = $conn->query($sql);
    
    $data = array();
    $arr = array();
    
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            
        }
    } else {
        echo "No Token";
    }
    print_r(json_encode($data));
    $conn->close();
    
?>

推荐答案

要么用户没有数据库所需的权限,要么密码错误.

Either the user does not have the required rights for the database or the password is wrong.

否则删除用户并使用以下语句创建:

Otherwise remove the user and use the following statement to create:

1.CREATE USER 'user'@'localhost' IDENTIFIED BY '123456789';
2.
3.GRANT ALL PRIVILEGES ON project.* TO 'user'@'localhost' WITH GRANT OPTION;

或者试试这个:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
//Create
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);

echo "Yaaay";

相关文章