<?php
$data = file_get_contents("php://input");
$json = json_decode($data);
mysql_connect("localhost", "root", "12345") or die("Could not connect");
mysql_select_db("db_shuttlebus") or die("Could not select database");
foreach($json as $obj){
echo $obj->_id;
}
?>
firebug json string
this is only 1 record json string {"_id":2,"Route_Seq":2,"Location_Name":"ABC","Route_LocationID":6,"Route_ID":"1","id":null}
this is 2 records, and work fine
[{"_id":2,"Route_Seq":1,"Location_Name":"perak","Route_LocationID":"6","Route_ID":"1","id":null},{"_id":1,"Route_Seq":2,"Location_Name":"TRY","Route_LocationID":"1","Route_ID":"1","id":null}]
Update : when json only 1 record, then it wont be loop,
if more than 1 record then it is working fine, why?
Simple: return a JSON array both times. foreach
iterates over arrays and you are not giving it one. There is nothing wrong with an array containing one element.
Your JSON for one record should look like this:
[{"_id":2,"Route_Seq":2,"Location_Name":"ABC","Route_LocationID":6,"Route_ID":"1","id":null}]
If you can't change the form of the data that is coming back then use the function is_array
to test it before looping, and handle one record as a special case.
Specifically, you can replace the loop at the bottom with something like this:
if(is_array($json)) {
foreach($json as $obj){
echo $obj->_id;
}
} else {
echo $json->_id;
}