Page 1 of 1

Call to a member function query() on a non-object

Posted: Sat Oct 12, 2013 9:07 am
by emekachibuzo
Hi. 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

Code: Select all

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

Re: Call to a member function query() on a non-object

Posted: Sat Oct 12, 2013 2:46 pm
by Christopher

Code: Select all

        $db = database::dataConnect();
        $result = $db->query($query); //This part is giving error
If $db is not an object then dataConnect() is not returning an object.

Re: Call to a member function query() on a non-object

Posted: Mon Oct 14, 2013 4:48 pm
by AbraCadaver
Maybe NOT isset():

Code: Select all

public static function  dataConnect()
{
    if(!isset(self::$db))
    {
            try
            {
                self::$db = new PDO(self::$dsn, self::$username, self::$password);