Reid
Reid

Reputation: 4534

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

 }
?>

Upvotes: 0

Views: 106

Answers (2)

Barmar
Barmar

Reputation: 780974

When you use the OO interface, the method names don't begin with mysqli_, that's only used for procedural calls. You also have no variable named $result, the result is in $r.

So it should be:

while ($row = $r->fetch_array(MYSQLI_ASSOC)) {

or:

while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {

Upvotes: 2

Daniel
Daniel

Reputation: 1253

You can iterate through mysqli_fetch_array();

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

Upvotes: 3

Related Questions