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?

2 Answers 2

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.

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

Comments

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

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.