Reid Reid - 1 month ago 9
Android Question

Get an array of JSON data from php database

I am kinda new to SQL and I am having a problem. I am following the tutorial from Here to try to get data from my database into my android app.

I have it working, but it only gets one line. I know it should be possible to iterate through the database and echo out every line that matches the ID to JSON, but I do not know how. How would I do this?

My current code:

<?php

if($_SERVER['REQUEST_METHOD']=='GET'){

$id = $_GET['id'];

require_once('dbConnect.php');

$sql = "SELECT * FROM LATLON WHERE DeviceID='".$id."'";

$r = mysqli_query($con,$sql);

$res = mysqli_fetch_array($r);

$result = array();

array_push($result,array(
"INDEX"=>$res['INDEX'],
"DeviceID"=>$res['DeviceID'],
"LAT"=>$res['LAT'],
"LON"=>$res['LON']
)
);

echo json_encode(array("result"=>$result));

mysqli_close($con);

}
?>





EDIT
I edited my code to this, but I am getting nothing. Still not quite understanding what is happening. Thanks for all the help!

<?php

if($_SERVER['REQUEST_METHOD']=='GET'){

$id = $_GET['id'];

require_once('dbConnect.php');

$sql = "SELECT * FROM LATLON WHERE DeviceID='".$id."'";

$r = mysqli_query($con,$sql);

while($row = $result->mysqli_fetch_array($r, MYSQLI_ASSOC)){
$array[] = $row;
}

echo json_encode($array);

mysqli_close($con);

}
?>

Answer

You can iterate through mysqli_fetch_array();

while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
        $array[] = $row;
}
echo json_encode($array);