简体   繁体   中英

How can I fetch all the rows of the data?

I have this code in 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;
}

Currently, I am taking only the last row at $response['data']. How could I transform this code in order to get all the $row values?

I tried initializing $response['data'] = array(); and then did $this->response['data'] = $row; but it didn't do the trick. Please note that I am a begginer in PHP.

You are overwriting your $response['data'] with each iteration of the while fetch loop and not appending to the array. Hence, the last record is the only one retained.

Consider the following adjustment where $data is its own array to hold row records of the SQL query resultset. Then this entire array object can be appended to the initial $response array (creating a nested setup):

 $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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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