I am trying to use json_encode() in a while loop while getting database results. Here is my code:

<?

$database = sqlite_open("thenew.db", 0999, $error);
if(!$database) die($error);

$query = "SELECT * FROM users";
$results = sqlite_query($database, $query);
if(!$results) die("Canot execute query");

while($row = sqlite_fetch_array($results)) {
  $data = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));

sqlite_close($database);

?>

The output of this is

{"response":"lastUserID lastUser lastXPos lastYPos"}

I want it to be...

{"response":["1 Alex 10 12", "2 Fred 27 59", "3 Tom 47 19"]}

etc.

So I want the json_encode() function to put ALL users into the array rather than the last one. How would I do this? Thanks

share|improve this question

3 Answers

up vote 3 down vote accepted

Try:

<?

$database = sqlite_open("thenew.db", 0999, $error);
if(!$database) die($error);

$query = "SELECT * FROM users";
$results = sqlite_query($database, $query);
if(!$results) die("Canot execute query");

$data = array();

while($row = sqlite_fetch_array($results)) {
  $data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));

sqlite_close($database);

?>
share|improve this answer
Thanks! It works. – Alex Aug 5 '11 at 22:51

Change this

while($row = sqlite_fetch_array($results)) {
  $data = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}

to

$data = array();
while($row = sqlite_fetch_array($results)) {
  $data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
share|improve this answer

Push each user to an array:

$data = array();
while($row = sqlite_fetch_array($results)) {
  $data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.