用户'root'@'localhost'访问被拒绝(使用密码:NO);

时间:2022-06-01 21:59:24

I'm using PHP amd mysql(XAMPP). I'm trying to connect my php file with database with PDO. But it shows following error. (mysql_query(): Access denied for user 'root'@'localhost' (using password: NO)). What is the problem that I don't know. I'm using PDO first time. Please anyone will tell me that what is the problem and what is the solution. Here is my code.

我正在使用PHP amd mysql(XAMPP)。我正在尝试将我的php文件与数据库与PDO连接。但它显示以下错误。 (mysql_query():用户'root'@'localhost'拒绝访问(使用密码:NO))。我不知道的问题是什么。我第一次使用PDO。请有人告诉我问题是什么,解决方案是什么。这是我的代码。

$dsn = 'mysql:dbname=abc;host=localhost';
$dbuser = 'user';
$dbpass = 'pass';

$params = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);

$pdo = new PDO($dsn, $dbuser, $dbpass, $params);

2 个解决方案

#1


$dsn = 'mysql:host=localhost;dbname=test';
$dbuser = 'user';
$dbpass = 'pass';

$params = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);

$pdo = new PDO($dsn, $dbuser, $dbpass, $params);

You r doing mistake here mysql:dbname=abc;host=localhost

你在这里做错了mysql:dbname = abc; host = localhost

                            ^^^^^^^^^^

#2


Well, you don't use mysql_query() with PDO. You would use $pdo->query(), or better yet $pdo->prepare() using a prepared statement.

好吧,你不要将mysql_query()与PDO一起使用。你可以使用$ pdo-> query(),或者更好的是$ pdo-> prepare()使用预准备语句。

mysql_query() is from the deprecated mysql API.

mysql_query()来自不推荐使用的mysql API。

$pdo = new PDO($dsn, $dbuser, $dbpass, $params);
$stmt = $pdo->prepare('SELECT * FROM `table` WHERE id = ?');
$stmt->execute( [ $_GET['id'] ] );
$row = $stmt->fetch();

#1


$dsn = 'mysql:host=localhost;dbname=test';
$dbuser = 'user';
$dbpass = 'pass';

$params = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);

$pdo = new PDO($dsn, $dbuser, $dbpass, $params);

You r doing mistake here mysql:dbname=abc;host=localhost

你在这里做错了mysql:dbname = abc; host = localhost

                            ^^^^^^^^^^

#2


Well, you don't use mysql_query() with PDO. You would use $pdo->query(), or better yet $pdo->prepare() using a prepared statement.

好吧,你不要将mysql_query()与PDO一起使用。你可以使用$ pdo-> query(),或者更好的是$ pdo-> prepare()使用预准备语句。

mysql_query() is from the deprecated mysql API.

mysql_query()来自不推荐使用的mysql API。

$pdo = new PDO($dsn, $dbuser, $dbpass, $params);
$stmt = $pdo->prepare('SELECT * FROM `table` WHERE id = ?');
$stmt->execute( [ $_GET['id'] ] );
$row = $stmt->fetch();