簡體   English   中英

如何獲取數據的所有行?

[英]How can I fetch all the rows of the data?

我在PHP中有以下代碼:

if (empty($_GET)) {
        $response['code'] = 1;
        $response['status'] = $api_response_code[$response['code']]['HTTP Response'];
        $sql = "SELECT * FROM table";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            // output data of each row
            while ($row = $result->fetch_assoc())
                    $response['data'] = $row;
        } else
            $response['data'] = NULL;
}

目前,我只在$ response ['data']的最后一行。 我如何轉換此代碼以獲得所有$ row值?

我嘗試初始化$response['data'] = array(); 然后執行$this->response['data'] = $row; 但這並不能解決問題。 請注意,我是PHP的入門者。

您正在使用while提取循環的每次迭代覆蓋$response['data'] ,而不是將其追加到數組中。 因此,最后一個記錄是唯一保留的記錄。

考慮以下調整,其中$data是其自己的數組,用於保存SQL查詢結果集的行記錄。 然后,可以將整個數組對象附加到初始$response數組(創建嵌套設置)中:

 $i = 0;
 $data = [];
 if ($result->num_rows > 0) {
     // output data of each row
     while ($row = $result->fetch_assoc()) {
            $data[$i] = $row;
            ...

            $i++;
     }
 }

 $response['data'] = $data;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM