how to fix Call to a member function prepare() on string

12,352

Your problem is here:

$db = DB();

If you were to var_dump() the $db variable you'd see it is equal to a string with a value of something like DB or DB().

It should be:

$db = new DB();
Share:
12,352
Yomi
Author by

Yomi

Updated on June 17, 2022

Comments

  • Yomi
    Yomi almost 2 years

    I have been trying to fix this error: PHP Fatal error: Call to a member function prepare() on string in /home/...../lib/library.php on line 91 I have also check this link: Reference - What does this error mean in PHP? and i don't seem to understand how to relate it to my problem at hand. Can anyone help? this is the script line affected:

    public function Login($username, $password)
        {
            try {
                $db = DB();
                $query = $db->prepare("SELECT user_id FROM users WHERE (username=:username OR email=:username) AND password=:password");
                $query->bindParam("username", $username, PDO::PARAM_STR);
                $enc_password = hash('sha256', $password);
                $query->bindParam("password", $enc_password, PDO::PARAM_STR);
                $query->execute();
                if ($query->rowCount() > 0) {
                    $result = $query->fetch(PDO::FETCH_OBJ);
                    return $result->user_id;
                } else {
                    return false;
                }
            } catch (PDOException $e) {
                exit($e->getMessage());
            }
        }
    
  • Preetika Kaur
    Preetika Kaur about 6 years
    Here DB is function not a class
  • Michele La Ferla
    Michele La Ferla almost 4 years
    Since db is a function here, how did you manage to solve the issue? I have the same problem.
  • Tom Wright
    Tom Wright almost 4 years
    If it is a function it needs to return an instance of a database class.