php - 是不是可以调用这个stmt fetch语句呢?

标签 php mysql oop

我是 PHP OOP 的新手,我在这里有一个问题。可以这样调用fetch语句吗? $this->stmt->fetch()?

我想做的是在我的类中定义 $stmt 变量并在不同的方法中使用它,即:

class Display {
 private $connection;
private $stmt;

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

public function selectUsersValues() {
    $query = "SELECT name, surname, employment_date FROM employee";
    $this->stmt = $this->connection->dbh->prepare($query);
    $this->stmt->execute();
}
public function displayUsersValues() {

        while ($employee = $this->stmt->fetch()){
         echo "<tr>";
         echo "<td>".$employee['name']."</td>";
         echo "<td>".$employee['surname']."</td>";
         echo "<td>".$employee['employment_date']."</td>";
    }
}
}

基本上,在一种方法中我只想选择值,而在另一种方法中获取所有结果。这是好事还是我必须在 selectUserValues 方法中做?

最佳答案

I am new to PHP OOP and I have a question here. Is it possible to call fetch sentence like this? $this->stmt->fetch()?

是的,这是可能的。

Is it good thing to do or I have to do it just in selectUserValues method?

不,这不是一件好事,因为您的客户端代码可以使用 displayUsersValues单独的方法。该方法与 selectUsersValues 有时间耦合。在您的代码中不明确的方法。 所以你应该force你的代码的用户(甚至可能是你,几周后)使用它们。你可以做这个重构:

class Display {
    private $connection;
    private $stmt;

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

    public function selectAndDisplayUsersValues() {
        $query = "SELECT name, surname, employment_date FROM employee";
        $this->stmt = $this->connection->dbh->prepare($query);
        $this->stmt->execute();
        $this->displayUsersValues();
    }

    private function displayUsersValues() {

            while ($employee = $this->stmt->fetch()){
             echo "<tr>";
             echo "<td>".$employee['name']."</td>";
             echo "<td>".$employee['surname']."</td>";
             echo "<td>".$employee['employment_date']."</td>";
             echo "</tr>";
        }
    }
}

注意:您的代码缺少 echo "</tr>";

关于php - 是不是可以调用这个stmt fetch语句呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42925944/

相关文章:

MySQL 多个左连接问题

php - Windows 上的 ApiGen。无法运行 apigen 命令

php - Laravel Eloquent 按关系排序

mysql - 使用临时的;使用文件排序..慢查询

Java mySQL登录问题

c++ - 没有公共(public)继承的类之间的链式转换

ios - MVC 通信,从 Swift 中的模型类更新标签

c - C中的状态机实现

php - 使用 Laravel 在 PostgreSQL 中插入空白数据

php - 当数据库中找不到值时如何中断循环