0

I have a page which creates an instance of a class. This class gets some information on the user (their badges) but when I return the object I only get the first record. Some code below.

$badges = new Badges; $result = $badges->getBadges($userID); $row_array[] = $result; echo json_encode($row_array); class Badges { function getBadges($userID) { $get_badge_query = mysqli_query($GLOBALS['connect'], "SELECT * FROM tbl_my_badges WHERE user_id = '" . $userID . "'"); while($get_badge_result = mysqli_fetch_assoc($get_badge_query)) { $result = array("done" => "true", "badge_icon" => $get_badge_result['badge_icon'], "badge_text" => $get_badge_result['badge_message']); } return $result; } } 

I have tried adding an array variable outside the loop and populating this with the results and returning the variable but still doesn't work.

Any help would be great.

4
  • Please explain what do you think $result = array("done" => "true",... line of code does. Commented Jun 27, 2013 at 2:15
  • Doesn't work means I still only get one result when I know there are more than that in the DB. Commented Jun 27, 2013 at 2:15
  • yep, I changed my comment. It's expected from your code :-) You don't store all the results but only the last one Commented Jun 27, 2013 at 2:16
  • What do you mean by "the first record", just 'badge_icon' or both 'badge_icon' and 'badge_message'? You are only SELECTing one record, unless you have multiple people with the same $userId. Commented Jun 27, 2013 at 2:28

1 Answer 1

2

You need to accumulate the results into an array, then return that:

$results = array(); while($get_badge_result = mysqli_fetch_assoc($get_badge_query)) { $results[] = array("done" => "true", "badge_icon" => $get_badge_result['badge_icon'], "badge_text" => $get_badge_result['badge_message']); } return $results; 

Otherwise you're just overwriting the $result variable on each iteration, and it will always be set to the last record in the DB.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I had to modify it slightly, not sure why but when I returned $results and tried to assign it to another array $row_array it still didn't work. So basically I have $row_array[] = $result and seems to work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.