1

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

3 Answers 3

4

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

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

Comments

3

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'];
}

Comments

3

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

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.