【问题标题】:PHP OOP: How to get database values and return all of themPHP OOP:如何获取数据库值并返回所有值
【发布时间】:2013-03-06 12:39:16
【问题描述】:

我正在尝试从数据库中获取所有结果并将它们返回到屏幕,问题是一旦我“回显”值它们都显示出来,但是当我使用“返回”时只有 1 显示出来。

我不能使用 echo,因为我的应用程序是基于将 html 放入函数的方式构建的,因此我可以填充对象,然后填充页面的内容。

这是我的代码。

public function read() {
    $query = "SELECT id, title, description, datetime FROM seminar";
    $result = $this->getDb()->query($query);

    while(($row = $result->fetchObject()) !== false) {
        foreach($row as $value) {
        return $row->title;
        //$this->setDescription($row->description);
        //$this->setDatetime($row->datetime);
        }
    } 
}

现在我想知道如何在屏幕上显示所有值,而不仅仅是现在显示的那个。

public function setSeminar($sem_obj) {
    $this->sem_obj = $sem_obj;
}

public function render() {
    $this->content = '
        On this page you can see all items.
    ';
    $this->content .= $this->sem_obj->getTitle();
    $this->content .= $this->sem_obj->getDescription();
    $this->content .= $this->sem_obj->getDatetime();
    //$this->content .= $this->text1->showSeminairs();
    return $this->content;
}

【问题讨论】:

    标签: php database function return echo


    【解决方案1】:

    使用数组.. 推送数据库对象并返回

    $tempArray=array();
    while(($row = $result->fetchObject()) !== false) {
    
          $tempArray['title']=$row->title;
         $tempArray['description']=$row->description;
          return $tempArray;
    
    } 
    

    【讨论】:

    • 函数在不同的类有关系吗?
    • 那不应该......如果你正确地调用 thr 类和函数
    • 我尝试了这样的示例: public function read() { $query = "SELECT id, title, description, datetime FROM研讨会"; $result = $this->getDb()->query($query); $values = 数组(); while(($row = $result->fetchObject()) !== false) { //foreach($row as $values) { $values['title'] = $row->title;返回$值; //$this->setDescription($row->description); //$this->setDatetime($row->datetime); //} } } 但我不知道如何填写渲染函数
    【解决方案2】:
    public function read() {
        $query = "SELECT id, title, description, datetime FROM seminar";
        $result = $this->getDb()->query($query);
        return $result;
    }
    

    在调用函数中,放入while循环并处理值。

    【讨论】:

    • 函数在不同的类有关系吗?
    • 这不是问题。无论您从哪里调用,它都会返回到函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2023-03-18
    • 2013-08-03
    相关资源
    最近更新 更多