致命错误:未捕获错误:在null上调用成员函数dbConnect()

时间:2018-05-03 07:48:00

标签: php pdo

请帮帮我..我的代码中有什么错误。我尝试创建登录表单并验证输入..

  

致命错误:未捕获错误:调用成员函数dbConnect()   空

(在$this->$db = $this->db->dbConnect();上)。

这是connection.php

<?php

class connection{

    public $db_host = 'localhost';
    public $db_name = 'login';
    public $db_user = 'root';
    public $db_pass = 'root';

    public function dbConnect()
    {
        try{
            $conn = new PDO("mysql:host=".$this->db_host.";dbname=".$this->db_name,$this->db_user,$this->db_pass);
           $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e)
        {
            echo 'ERROR: ' . $e->getMessage();
        }    
        return $this->conn;
    }
}

?>

这是login.php

<?php

include_once('connection.php');

class User{

    private $db;
    public function __construct(){

        $this->$db = new connection();
        $this->$db = $this->db->dbConnect();

    }

    public function isAuthenticated($name, $pass){

        if(!empty($name) && !empty($pass)){

            $st = $this->$db->prepare("SELECT * FROM loginUser WHERE username =? AND password =?");
            $st->bindParam(1, $name);
            $st->bindParam(2, $pass);
            $st->execute();

            if($st->rowCount() == 1){
                echo "User Verified";
            }else{
                echo "Incorrect UserName or Password";
            }

        }else{

            echo "Please Enter User Name And Password";
        }

    }



}

?>

1 个答案:

答案 0 :(得分:2)

替换它:

    $this->$db = new connection();
    $this->$db = $this->db->dbConnect();

用这个:

    $this->db = (new connection())->dbConnect();

而且:

$this->$db->prepare

用这个:

$this->db->prepare

实际上,在每个地方都应该替换:

$this->$db

$this->db