简体   繁体   中英

Access denied for user 'root'@'localhost' (using password: NO);

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.

$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);
$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

                            ^^^^^^^^^^

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() is from the deprecated mysql API.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM