Nikhil Sindhu Nikhil Sindhu - 3 months ago 15
MySQL Question

OOP login authentication php code

I am getting an error which is like this ---------- Uncaught Error: Call to a member function query() on null in C:\xampp\htdocs\try\index.php:7 Stack trace: #0 {main} thrown in C:\xampp\htdocs\try\index.php on line 7

code is written below

<?php

class DB{

private static $_instance = NULL;

private $_pdo , $_query , $_error = false, $_results, $_count = 0;

public function __construct(){

try{
$this->_pdo = new PDO('mysql:host='.Config::get('mysql/host').';dbname='.Config::get('mysql/dbname'),Config::get('mysql/username'),Config::get('mysql/password'));

echo'connected';
}

catch(PDOException $e){

$e->getMessage();
}
}

public static function getInstance(){

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

self::$_instance = new DB;

}

else{

return self::$_instance;
}

}

public function sqlQuery($query){

$this->_error = false;

if($this->_query = $this->_pdo->query($query)){
echo'ok';
}
}



}
?>


And here is the index page

<?php

require_once 'core/init.php';

$user = DB::getInstance();

$user -> query('SELECT * FROM user');

?>

mnv mnv
Answer

getInstance() in your code dont return instance in first time. Edit this method:

public static function getInstance()
{
    if (!isset(self::$_instance))
    {
        self::$_instance = new DB;
    }

    return self::$_instance;
}

UPDATE

Why you have $user equals to null after this line: $user = DB::getInstance();? Look into your realisation of getInstance(). What happens when you execute it first time:

public static function getInstance(){
    // At first time self::$_instance equals to null,
    // therefore !isset(self::$_instance) is true
    if(!isset(self::$_instance)){
        // So, at first time this branch executed.
        self::$_instance = new DB;
        // What we return at first time? 
        // Nothing, because no "return" statement here.
    }

    else{
        // So, this branch will be executed at second and next times.
        // Therefore at second and next times getInstance() will return instance.
        return self::$_instance;
    }

}

How to write getInstance() correctly? Just remove else from this code like in answer above.