1

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?

5
  • look at the thable, there is a filed called "unique_id" ? Commented Feb 3, 2017 at 7:05
  • yes, there is no problem with the db' Commented Feb 3, 2017 at 7:05
  • I just checked out the table and the column names are fine. They are literally unique_id, name, and email. The order is a little bit different though. Commented Feb 3, 2017 at 7:09
  • put index value instead of name of the table column like 0,1,2 as answer by @Anant use assoc instead row Commented Feb 3, 2017 at 7:11
  • @Anant I just fixed the problem with your tip. You saved my day!! Commented Feb 3, 2017 at 7:50

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Marshall S. Lee glad to help you
1
<?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);
}
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.