user2071763
user2071763

Reputation: 37

A simple Query Builder

I try to build an Laravel like query builder, but i get an problem.

Fatal error: Call to a member function fetch() on a non-object in C:\xampp\htdocs\tutorial\public\classes\DB.php on line 31

class DB {
    private $_pdo,
    $_query,
    $_results = array(),
    $_count = 0;

    public static $instance;

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

    public function __construct(){
        try {
            $this->_pdo = new PDO('mysql:host=localhost;dbname=query', 'root', '');

            $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }
    }

    public function query($sql){
        if($this->_pdo = $this->_pdo->query($sql)){

           while($row = $this->_query->fetch(PDO::FETCH_OBJ)){
               $this->_results[] = $row;

           }
        }
        return $this;
 }

 public function results(){

     return $this->_results;
 }

}

Upvotes: 0

Views: 780

Answers (2)

Michał Prajsnar
Michał Prajsnar

Reputation: 672

Change:

if($this->_pdo = $this->_pdo->query($sql)){

To:

if($this->_query = $this->_pdo->query($sql)){

EDIT:

Would be even better in this situation if your $_query was called $_resource.

EDIT 2:

For the future - you shoud check what kind of SQL you actually query in your query method - maybe it would be nice if for UPDATE... it returns / sets somewhere in your object affected rows and for INSERT... it returns / sets last insert id?

That would make it much more flexible - just a suggestion though :)

EDIT 3:

Make sure your $sql is safe / injection proof - for PDO use prepared statements:

PDO::prepare - Manual

Upvotes: 3

Bad Wolf
Bad Wolf

Reputation: 8349

$this->_query is never being set in your query function. You are assigning $this->_pdo to the result of the query instead of the query variable.

Upvotes: 0

Related Questions