简体   繁体   English

在OOP PHP中重构代码并使用PDO进行mysql查询

[英]Refactoring code in OOP PHP and using PDO for mysql queries

I am new to OOP in PHP. 我是PHP的OOP新手。 I am having a problem while I am trying to refactor my code in OOP and PDO. 当我试图在OOP和PDO中重构我的代码时,我遇到了问题。 The problem occurred when I tried refactor my code. 我尝试重构代码时出现问题。 So I have a category class to manage category CRUD operations. 所以我有一个类别类来管理类别CRUD操作。 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 - 我正在调用我的页面中的read all方法,如下所示 -

 $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 " “ 提前致谢 ”

your second readAll() method returns nothing. 你的第二个readAll()方法什么都不返回。 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. 除了这个小问题,doQuery()方法有一个错误,使它完全没用。 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 允许您使用占位符来表示查询中的实际数据变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM