Roy Coder
Roy Coder

Reputation: 33

Refactoring code in OOP PHP and using PDO for mysql queries

I am new to OOP in PHP. I am having a problem while I am trying to refactor my code in OOP and PDO. The problem occurred when I tried refactor my code. So I have a category class to manage category CRUD operations. To read all the previously created categories I have a method

    public function readAll(){
        $query = "SELECT * FROM " . $this->table_name . " ORDER  BY modified ASC";
       $stmt = $this->connection->prepare($query);
         if($stmt->execute()){
            return $stmt;
          } 
  }

And within the same class in the construct function I am getting my db connection like so

public function __construct(PDO $db){
    $this->connection = $db;
} 

and I am calling the read all method in my page like this -

 $allCategories= $category->readAll();

and it works just fine but when I tried to refactor my code to use a new function like this-

    private function doQuery($query){
        $stmt = $this->connection->prepare($query);
         if($stmt->execute()){
            return $stmt;
          }    
    }
    public function readAll(){
        $query = "SELECT * FROM " . $this->table_name . " ORDER  BY modified ASC";
      $this->doQuery($query);
  }

I am getting the following error :

Fatal error: Call to a member function fetch() on a non-object in D:\xampp\htdocs\image-upload\category.php on line 222

So I just want to save myself from having to write prepare and execute statements every time I make a different query. I am trying to make my code DRY. I may be missing something. A slight hint in the right direction is highly appreciated. Please help me.

" THANKS IN ADVANCE "

Upvotes: 3

Views: 497

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157887

your second readAll() method returns nothing. It should read

return $this->doQuery($query);

or, rather, based on the method's name

return $this->doQuery($query)->fetchAll();

to get an array with all the rows selected.

Aside from this trifle issue, there is a mistake in the doQuery() method, making it utterly useless. It have to be

private function doQuery($query, $data = array()){
    $stmt = $this->connection->prepare($query);
    $stmt->execute($data);
    return $stmt;
}

allowing you to use placeholders to represent actual data variables in the query

Upvotes: 3

Related Questions