Uncaught Error: Call to a member function prepare(

2019-09-20 00:12发布

Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\xampp\htdocs\PDO\config\DB.php:21 Stack trace: #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} thrown in C:\xampp\htdocs\PDO\config\DB.php on line 21

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();
    }

}

标签: php
1条回答
等我变得足够好
2楼-- · 2019-09-20 00:20

Change the statement from

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

into

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

You need to create pdo object if it doesn't exist

查看更多
登录 后发表回答