【问题标题】:Array only returns last item, when using fetch使用 fetch 时,数组仅返回最后一项
【发布时间】:2023-03-11 09:45:01
【问题描述】:

我正在尝试将数据库结果返回到数组。使用 fetch 时,它只返回数组中的最后一项。

如果我写 $result[$this->topic] .= $a 而不是 $result[$this->topic] = $a,则数组会返回所有项目,但只在一个字符串中。

来自我的数据库类的函数,带有 while 循环:

        public function GetTopic($stmt) {

        if ($stmt->execute() == false) {
            throw new Exception($this->mysqli->error);
        }

        $stmt->bind_result($a); 
        $result = array();

        while ($stmt->fetch()) {
            $result[$this->topic] = $a;
        }

        $stmt->close();

        var_dump($result);
        return $result;
    }

来自我的处理程序类的函数,我从数据库类调用函数:

        public function GetTopics() {

        $query = "SELECT Topic FROM question";
        $stmt = $this->db->Prepare($query);
        $result = $this->db->GetTopic($stmt);

        return $result;
    }

我也尝试过使用 num_rows 和 store_result 而不是 fetch,这也不起作用。任何帮助表示赞赏。

【问题讨论】:

    标签: php arrays while-loop return fetch


    【解决方案1】:
    $result[$this->topic][] = $a;
    

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 2013-11-02
      • 2014-02-21
      • 2014-04-24
      • 1970-01-01
      相关资源
      最近更新 更多