未捕获的错误:调用成员函数prepare()

时间:2017-02-08 18:03:28

标签: php

  

致命错误:未捕获错误:调用成员函数prepare()   C:\ xampp \ htdocs \ PDO \ config \ DB.php中的null:21堆栈跟踪:#0   C:\ xampp \ htdocs \ PDO \ config \ Student.php(14):DB :: prepare(' SELECT * FROM   t ...')#1 C:\ xampp \ htdocs \ PDO \ index.php(60):Student-> readall()#2   {main}在第21行的C:\ xampp \ htdocs \ PDO \ config \ DB.php中抛出

db.php中

class DB{
    private static $pdo;

    public function connection(){
        if(isset(self::$pdo)) {

            try{
                self::$pdo = new PDO ("mysql:host=".DB_HOST.";dbname=",DB_USER,DB_PASS);
                echo "Conncetion successfully";

            }catch(PDOException $e){
                echo "Conection Failed............".$e->getMessage();
            }
        }
        return self::$pdo;
    }
    public static function prepare($sql){ // own prepare() method
        return self::connection()->prepare($sql); //pdo prepare()
    }
}

Student.php

include "DB.php";

class Student{
    //private $table = "tb_user";

    public function readall()
    {

        //$sql = "SELECT * FROM $this->table";

        $sql = "SELECT * FROM tb_user";
            $stmt = DB::prepare($sql);
            $stmt->exceute();
            return $stmt->fetchAll();
    }

}

1 个答案:

答案 0 :(得分:0)

更改声明
 if(isset(self::$pdo)) {

进入

 if( ! isset(self::$pdo)) {

如果pdo对象不存在,则需要创建