marshallslee
marshallslee

Reputation: 655

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.


Notice: Undefined index: unique_id in /storage/h3/859/644859/public_html/searchfriends.php on line 20

Notice: Undefined index: name in /storage/h3/859/644859/public_html/searchfriends.php on line 21

Notice: Undefined index: email in /storage/h3/859/644859/public_html/searchfriends.php on line 22

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?

Upvotes: 1

Views: 1158

Answers (2)

Haninder Singh
Haninder Singh

Reputation: 618

<?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);
}
?>

Upvotes: 1

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

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

Upvotes: 2

Related Questions