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();
}
}
Change the statement from
into
You need to create
pdo
object if it doesn't exist