Call to a member function prepare() on a non-object in (Fatal error)

后端 未结 2 1868
青春惊慌失措
青春惊慌失措 2021-01-29 10:34

Fatal error: Call to a member function prepare() on a non-object in G:\\xampp\\htdocs\\live\\Billing Suryas\\model\\DBConfig.php on line 28

<
2条回答
  •  抹茶落季
    2021-01-29 10:50

    You are trying to store the DB connection handle in a variable $conn. But that is just a local variable, not the class property $conn. To use the later you have to access it is $this->conn.

    So your connection method should be something like

    public function dbConnection()
    {
        try {
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
        } catch(PDOException $exception) {
            echo "Connection error: " . $exception->getMessage();
        }
    }
    

    Given that you now can use $this->conn in other functions

    public function login($usname, $uspswd)
    {
        try {
            $stmt = $this->conn->prepare("select * from users where user_name=:uname and password=:paswrd and permission='0' and delet='0'");
            $stmt->execute(array(':uname'=>$usname, ':paswrd'=>$uspswd));
            $userRow = $stmt->fetch(PDO::FETCH_ASSOC);
            if($stmt->rowCount() == 1) {
                if(password_verify($uspswd, $userRow['password'])) {
                    $_SESSION['user_session'] = $userRow['user_id'];
                    return true;
                } else {
                    return false;
                }
            }
        } catch(PDOException $exception) {
            echo $exception->getMessage();
        }
    }
    

    In other words: using $conn instead of $this->conn does not refer to the objects property $conn, but a local variable $conn in the methods. But local variables are not persistent. So once you leave the method dbConnection() and try to reuse that variable by picking the same name in login(), the identifier $conn actually refers to two different local variables. Which of course means that it does not hold any value in the login() method which leads to the error you receive.

    There are other approaches to this like "injecting the connection object" into your methods. But the above is a clean and usually preferred approach.

提交回复
热议问题