-2

Please I need help with the code below; I get

Connection error: SQLSTATE[HY000][1045] Access denied for user 'root'@'localhost' (using password: NO).

After this error, I get another below it that shows:

Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\wamp64\www\user_login\objects\user.php on line 41

Then the third one shows:

Error: Call to a member function prepare() on null in C:\wamp64\www\user_login\objects\user.php on line 41

I am still new to working with class; Please help me out. Thanks

Please find my code below:

<?php
// used to get mysql database connection
class Database{

    // specify your own database credentials
    private $host = "localhost";
    private $db_name = "phplogin";
    private $username = "root";
    private $password = "";
    public $conn;

    // get the database connection

    public function getConnection(){

        $this->conn = null;
 
        try{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }
 
        return $this->conn;
    }

}

?>

Error message screenshot

Additional Code based on the error

<?php
// 'user' object

//require_once './config/database.php';

class User{
 
    // database connection and table name
    private $conn;
    private $table_name = "users";
 
    // object properties
    public $id;
    public $firstname;
    public $lastname;
    public $email;
    public $contact_number;
    public $address;
    public $password;
    public $access_level;
    public $access_code;
    public $status;
    public $created;
    public $modified;
 
    // constructor
    public function __construct($db){
        $this->conn = $db;
    }

    // check if given email exist in the database
    function emailExists(){
 
    // query to check if email exists
    $query = "SELECT id, firstname, lastname, password, access_level, status
            FROM " . $this->table_name . "
            WHERE email = ?
            LIMIT 0,1";
 
    // prepare the query
    $stmt = $this->conn->prepare($query);
 
    // sanitize
    $this->email=htmlspecialchars(strip_tags($this->email));
 
    // bind given email value
    $stmt->bindParam(1, $this->email);
 
    // execute the query
    $stmt->execute();
 
    // get number of rows
    $num = $stmt->rowCount();
 
    // if email exists, assign values to object properties for easy access and use for php sessions
    if($num>0){
 
        // get record details / values
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
 
        // assign values to object properties
        $this->id = $row['id'];
        $this->firstname = $row['firstname'];
        $this->lastname = $row['lastname'];
        $this->access_level = $row['access_level'];
        $this->password = $row['password'];
        $this->status = $row['status'];
 
        // return true because email exists in the database
        return true;
    }
 
    // return false if email does not exist in the database
    return false;
   }

   // create new user record
   function create(){
 
    // to get time stamp for 'created' field
    $this->created=date('Y-m-d H:i:s');
 
    // insert query
    $query = "INSERT INTO
                " . $this->table_name . "
            SET
                firstname = :firstname,
                lastname = :lastname,
                email = :email,
                contact_number = :contact_number,
                address = :address,
                password = :password,
                access_level = :access_level,
                status = :status,
                created = :created";
 
    // prepare the query
    $stmt = $this->conn->prepare($query);
 
    // sanitize
    $this->firstname=htmlspecialchars(strip_tags($this->firstname));
    $this->lastname=htmlspecialchars(strip_tags($this->lastname));
    $this->email=htmlspecialchars(strip_tags($this->email));
    $this->contact_number=htmlspecialchars(strip_tags($this->contact_number));
    $this->address=htmlspecialchars(strip_tags($this->address));
    $this->password=htmlspecialchars(strip_tags($this->password));
    $this->access_level=htmlspecialchars(strip_tags($this->access_level));
    $this->status=htmlspecialchars(strip_tags($this->status));
 
    // bind the values
    $stmt->bindParam(':firstname', $this->firstname);
    $stmt->bindParam(':lastname', $this->lastname);
    $stmt->bindParam(':email', $this->email);
    $stmt->bindParam(':contact_number', $this->contact_number);
    $stmt->bindParam(':address', $this->address);
 
    // hash the password before saving to database
    $password_hash = password_hash($this->password, PASSWORD_BCRYPT);
    $stmt->bindParam(':password', $password_hash);
 
    $stmt->bindParam(':access_level', $this->access_level);
    $stmt->bindParam(':status', $this->status);
    $stmt->bindParam(':created', $this->created);
 
    // execute the query, also check if query was successful
    if($stmt->execute()){
        return true;
    }else{
        $this->showError($stmt);
        return false;
    }
 
}

public function showError($stmt){
     echo "<pre>";
         print_r($stmt->errorInfo());
     echo "</pre>";
}

}

?>
jarlh
  • 42,561
  • 8
  • 45
  • 63
eni4real
  • 1
  • 2
  • Did you set a password on the MySQL `root` userid? – RiggsFolly Jan 26 '22 at 10:39
  • Its always better to create a user in MySQL, that is related to just this site you are building. Give it a password, And set its privilages to allow it access to only this one database you are using for this one site. Will make moving it to a live site easier later as well – RiggsFolly Jan 26 '22 at 10:40
  • Check that your issue of WAMP is running. For instance, if you have PHPMyAdmin installed, or use MySQL Workbench, can you access with that? – Shaun Bebbers Jan 26 '22 at 10:40
  • Never configure your web app to login to the database as `root`. Root can do whatever it likes, so if your PDO code has any unexpected vulnerabilities this just leaves your database an open book for hackers. Instead create a separate user account specifically for this application which has only the permissions it actually _needs_ in order to work properly. Don't even use the root account as a shortcut during development or testing, because you need to test your account permissions as well - otherwise when you go live you might have unexpected errors relating to the user account setup. – ADyson Jan 26 '22 at 10:45
  • @ShaunBebbers it wasn't running, there would be a connection error, not a permissions error... – ADyson Jan 26 '22 at 10:45
  • And if WAMPServer is running, also chech that MYSQL is started. Hover your mouse over the WAMPManager icon in the System Tray.... 1. Is it green? 2. When you hover, do you see a tooltip saying `local server. All services are running`? – RiggsFolly Jan 26 '22 at 10:45
  • 1
    P.S. The subsequent errors with `prepare()` are a consequence of the fact that you do not tell the code to halt when a connection failure occurs. You've caught the exception, echoed the error, and then allowed the program to continue regardless, meaning it will still attempt to run queries without having a valid connection. It tries to use a `null` variable as the connection object. That's not very logical... – ADyson Jan 26 '22 at 10:47
  • 1
    P.P.S. Don't use htmlspecialchars or strip_tags on any of your input data. It's unnecessary and at best will do nothing useful. At worse it will corrupt or change the data in ways you didn't expect. You don't need to sanitise input data in this way. You only need these functions when you're _outputting_ the data - and even then, only into a context where the things they're sanitising would be a potential danger. E.g. it makes sense to encode HTML tags when you're outputting the content into a web page, but it would be pointless if you were outputting the same content to a CSV report file. – ADyson Jan 26 '22 at 10:50
  • Thanks all. I have just created another phpmyadmin login account with Password, but I still get this message: Connection error: SQLSTATE[HY000] [1045] Access denied for user 'adminphp'@'localhost' (using password: YES) ( ! ) Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\wamp64\www\user_login\objects\user.php on line 39 ( ! ) Error: Call to a member function prepare() on null in C:\wamp64\www\user_login\objects\user.php on line 39 Call Stack – eni4real Jan 26 '22 at 12:00
  • Sounds like you either haven't given the correct password in the php code, or you haven't configured that username to be available via localhost – ADyson Jan 26 '22 at 12:25
  • Does this answer your question? [Access denied for user 'root@localhost' (using password:NO)](https://stackoverflow.com/questions/2995054/access-denied-for-user-rootlocalhost-using-passwordno) – Cristik Feb 04 '22 at 06:35

1 Answers1

0

If you are using MariaDb locally, you may set up a user like this:

CREATE USER 'databaseUser'@localhost IDENTIFIED BY 'databasePassword';
GRANT ALL PRIVILEGES ON databaseName.* TO 'databaseUser'@localhost;
FLUSH PRIVILEGES;

Line one creates the user and password.

Line two will grant that user access to each Database on your localhost.

Line three is necessary to ensure that our user has the necessary privileges to its database.

You then use the user and password set as above in your PHP script. I use MySQL Workbench as a tool to work with my Databases locally; here I run my SQL scripts as above.

You may view all users with

SELECT * FROM mysql.user;
Shaun Bebbers
  • 179
  • 2
  • 12