Reputation: 21
I'm a beginner in PHP. I'm trying to get data from database but I'm having the following error "Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\phpExamPrep\studentDB.php on line 22" I'm sorry I have to include all the codes, its just to help you help me. Thanks I have the following classes
class database
{
private static $dsn = 'mysql:local=localhost;dbname=test1';
private static $username ='me';
private static $password ='me';
public static $db;
private function __construct()
{
}
public static function dataConnect()
{
if(isset(self::$db))
{
try
{
self::$db = new PDO(self::$dsn, self::$username, self::$password);
}
catch(PDOException $e)
{
$error_message = $e->getMessage();
include 'database_error.php';
exit();
}
}
return self::$db;
}
}
class studentDB
{
public static function getAllRecords()
{
require 'database.php';
$query = 'select * from student';
$db = database::dataConnect();
$result = $db->query($query); //This part is giving error
$students = array();
foreach($result as $row)
{
$stud = new student($row['firstname'],$row['lastname']);
$stud->setID($row['id']);
$students[]=$stud;
}
return $students;
}
}
<?php
include 'studentDB.php';
$stx =studentDB::getAllRecords();
foreach ($stx as $r)
{
echo $r->getFirstName().' '.$r->getLastName().' '.$r->getID();
}
?>
when I changed if(isset(self::$db)) to if(!isset(self::$db)), the error becomes
"Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\phpExamPrep\studentDB.php on line 25"
Upvotes: 0
Views: 239
Reputation: 7812
I think this
if(isset(self::$db))
must be changed in
if ( ! isset(self::$db) )
as you want to set self::$db
if it's not set already and not the opposite.
From the code fragment that you posted in fact, it looks like this call
$db = database::dataConnect();
is returning a null reference to $db
and therefore you cannot call query
on a null reference.
Upvotes: 1