donglaoping9702 2013-11-18 18:26
浏览 124
已采纳

访问被拒绝用户'admin'@'localhost'mysql

I created a database via:

create database test_db;

Then I created a user via:

CREATE USER 'test_user'@'test_db' IDENTIFIED BY 'test_pass';
grant all privileges on *.* to 'test'@'test';

now when i try to connect to it via PHP, i used the following code:

    $hostname_localhost ="localhost";  
    $database_localhost ="test_db";  
    $username_localhost ="test_user";  
    $password_localhost ="test_pass";  
    try{
        $dbh = new PDO("mysql:host=$hostname_localhost;dbname=$database_localhost",$username_localhost,$password_localhost);
        echo 'Connected to DB'.'<br />';
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $dbh->prepare("SELECT user,host from mysql.user");
        $stmt->execute();

        $result = $stmt->fetchAll();

        foreach($result as $row)
        {
            echo $row['user'].'@'.$row['host'].'<br />';
        }

        $dbh = null;
    }
    catch(PDOException $e)
    {
        echo $e->getTraceAsString().$e->getLine().$e->getMessage();
    }

I am getting the following error:

SQLSTATE[28000] [1045] Access denied for user 'test_user'@'localhost' (using password: YES)

please tell me how to fix this. how do i connect to my test user via PHP.

  • 写回答

1条回答 默认 最新

  • duannaxin9975 2013-11-18 18:28
    关注

    Your create user / grant should be:

    CREATE USER 'test_user'@'localhost' IDENTIFIED BY 'test_pass';
    grant all privileges on test_db.* to 'test_user'@'localhost';
    

    I also noticed your SQL Select statement is from mysql.user. If you want test_user to have access to query from that database, you would need another GRANT statement and or change the test_db part in the grant statement to *. I am not sure what your use case is and or what you need, but just a heads up.

    The syntax for the Create User goes as follows:

    CREATE USER 'username'@'host_or_IPAddress' IDENTIFIED BY 'password';
    

    For the grant it is (omitted a few items, please read the referenced material for more in depth options / information):

    GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'samehostascreateuser';
    

    For your reference / reading: MySQL Create User and Mysql Grant Syntax

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行