1

I am using JSON in my php pages. I am formatting json data from my mysql datebase. But somehow json data is not formatted correctly.

I have

{"imei":"44fd02f38e4a5c0c","dolgota":"49.406","shirota":"53.5412","date":"2014\/05\/13 13:24:16"}{"imei":"a2422857b2cccf4c","dolgota":"49.4385","shirota":"53.5142","date":"2014\/05\/13 11:22:09"}

but what I want

[{"imei":"44fd02f38e4a5c0c","dolgota":"49.406","shirota":"53.5412","date":"2014\/05\/13 13:24:16"},{"imei":"a2422857b2cccf4c","dolgota":"49.4385","shirota":"53.5142","date":"2014\/05\/13 11:22:09"}]

this is my code

$dbh = mysql_connect($host, $user, $pswd) or die("Не могу соединиться с MySQL.");
mysql_select_db($database) or die("Не могу подключиться к базе.");
$query = "SELECT * FROM `kordinates`";
$res = mysql_query($query);
while($row = mysql_fetch_array($res))
{
    $json_data = array('imei'=>$row['imei'],'dolgota'=>$row['dolgota'],'shirota'=>$row['shirota'],'date'=>$row['date']);
    echo json_encode($json_data);
}

How I can do it?

shatheesh
  • 633
  • 6
  • 10
user3176367
  • 135
  • 1
  • 3
  • 8

2 Answers2

2

First take all data in array and then use json_encode after your loop complete,

while($row = mysql_fetch_array($res))
{
    $json_data[] = array('imei'=>$row['imei'],'dolgota'=>$row['dolgota'],'shirota'=>$row['shirota'],'date'=>$row['date']);       
}
echo json_encode($json_data);

Waring: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Rikesh
  • 26,156
  • 14
  • 79
  • 87
0

then just put your array in an array:

$json_data = 
array(array('imei'=>$row['imei'],'dolgota'=>$row['dolgota'],'shirota'=>$row['shirota'],'date'=>$row['date']));
kennypu
  • 5,950
  • 2
  • 22
  • 28