简体   繁体   中英

PHP - get multiple rows from MySQL and JSON-encode them

I'm trying to get a JSON array from the MySQL database. Here's the part of the code that fetches rows and add them into the array.

<?php
if($rowcount > 0) {
    while($row = mysqli_fetch_row($fetch)) {
        $row_array["uid"] = $row['unique_id'];
        $row_array["users"]["name"] = $row['name'];
        $row_array["users"]["email"] = $row['email'];
        array_push($users, $row_array);
    }
    mysqli_free_result($fetch);
    echo json_encode($users);
}
?>

This part is causing an error, showing the following message.


: Undefined index: unique_id in on line :未定义索引:第 unique_id

: Undefined index: name in on line :未定义的索引:第行的名称

: Undefined index: email in on line :未定义的索引:第行的电子邮件

Each line represents the following parts.

$row_array["uid"] = $row['unique_id'];
$row_array["users"]["name"] = $row['name'];
$row_array["users"]["email"] = $row['email'];

So, I believe I did not properly format the array. How should I fix it correct?

Based on manual :- http://php.net/manual/en/mysqli-result.fetch-row.php

It will give you a numeric indexes array. So you have to do like below:-

$row[0],$row[1].... so on

OR

Best should be change this single line like below:-

while($row = mysqli_fetch_assoc($fetch)) { 
// instead of mysqli_fetch_row use mysqli_fetch_assoc
<?php
if($rowcount > 0){
    while($row = mysqli_fetch_row($fetch)) {
echo "<pre>";
 print_r($fetch); //  check here you have columns of email ,name etc.. or not
 die;
        $row_array["uid"] = $row['unique_id'];
        $row_array["users"]["name"] = $row['name'];
        $row_array["users"]["email"] = $row['email'];
        array_push($users, $row_array);
    }
    mysqli_free_result($fetch);
    echo json_encode($users);
}
?>

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