skip to Main Content

I am running MySQL Server version: 5.7.25-0ubuntu0.16.04.2 – (Ubuntu).

When I run this php script below with the CORRECT MySQL root user password entered I get the error:
Access denied for user ‘root’@’localhost’ (using password: NO)

However if I change the root user to an INCORRECT value I get the MySQL error:
Access denied for user ‘root’@’localhost’ (using password: YES)

I know the MySQL root user password I’m entering is correct because I can log into both the mysql command line and phpmyadmin with it.

So the CORRECT password when received by MySQL is returning access denied using password NO but I don’t understand why it would do that. Any help is much appreciated.

<?php 
  $dbusername = "root"; 
  $dbpassword = "password"; 
  $dbname = "DB"; 
  $dbtable = "table_name"; 

  $con=mysqli_connect("localhost",$dbusername,$dbpassword,$dbname); 
  // Check connection 
  if (mysqli_connect_errno()) 
  { 
    echo " " . mysqli_connect_error(); 
  } 
?>

2

Answers


  1. Chosen as BEST ANSWER

    Just in case anyone has the same problem, it turned out that the issue was the MySQL password I was using started with the character $. The mysql command line program and phpmyadmin had no problem with accepting this character in the password but when it was included as part of a mysqli connection string (or PDO connection string for that matter) it would throw the 1045 Access Denied Using Password: NO error.

    I changed the password's first character to # and no more error.


  2. Assuming you mysql / root user password is Pass123. Connect to Mysql Shell and run below sql statements.

    GRANT USAGE ON *.* to `root`@`%` IDENTIFIED BY 'Pass123';
    GRANT ALL PRIVILEGES ON *.* TO `root`@`%` WITH GRANT OPTION;
    flush privileges;
    

    Now update info in php and run PHP again.

    <?php 
    $dbusername = "root"; 
    $dbpassword = "Pass123"; 
    $dbname = "DB"; 
    $dbtable = "table_name"; 
    

    It is recommended to create a non root user to use in the application. In my answer, I have used root as you have used this user in your question.
    See create-new-user-grant-permissions-mysql

    Don’t forget to change database and table names.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search