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

February 17, 2015 5.6k views

First off I connect using this code here.

$mysqli = new mysqli("localhost", $username, $password, $database);

This works fine, I log in under root, (I know I should create a new user for security, but this so far is just a proof of concept)
However when I attempt to do a query such as

$sql = "SELECT 
                        user_id,
                        user_name,
                        user_level
                    FROM
                        users
                    WHERE
                        user_name = '" . mysql_real_escape_string($_POST['user_name']) . "'
                    AND
                        user_pass = '" . sha1($_POST['user_pass']) . "'";

            $result = mysql_query($sql);

It gives me the errors message Access denied for user 'admin'@'localhost' (using password: NO).
I don't know why this is happening. Do I need to configure mysql a certain way?

1 Answer

You're connecting with MySQLi but you are using MySQL functions (which are also deprecated).

  • I changed them, however the query still fails for some reason. For example this one here.
    $sql = "INSERT INTO
    users(username, userpass, useremail ,userdate, userlevel)
    VALUES('" . mysqli
    realescapestring($POST['username']) . "',
    '" . sha1($POST['userpass']) . "',
    '" . mysqlirealescapestring($POST['user_email']) . "',
    NOW(),
    0)";
    Am I just messing up on syntax? There is no error message given, so I don't know what's wrong.

  • That function doesn't exist, and the problem is with mysql_query.

  • MySQLi's syntax is actually different so you will need to change a few things -- check out How to Use PHP Improved MySQLi extension (and Why You Should).

    $mysqli = new mysqli("localhost", $username, $password, $database);
    
    $query = $mysqli->prepare("SELECT 
                            user_id,
                            user_name,
                            user_level
                        FROM
                            users
                        WHERE
                            user_name = ?
                        AND
                            user_pass = ?");
    
    $query->bind_param('ss', $POST['username'], sha1($_POST['user_pass']));
    $query->execute();
    $query->bind_result($user_id, $user_name, $user_level);
    $query->fetch();
    
  • Also, please don't store passwords as SHA1 hashes in your database. It's a bad security practice. Consider using Bcrypt instead: mysql - Using PHP 5.5's password_hash() and verify function, am I doing it right? - Stack Overflow

Have another answer? Share your knowledge.