PHP json_encode() at following code:
$con = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$query = "SELECT * FROM data limit 1" ;
$results = $con->query($query);
$return = array();
if($results) {
while($row = $results->fetch_assoc()) {
$return[] = $row;
}
}
echo json_encode($return);
$con->close();
creates a JSON object like this:
[{"id":"1","name":"tabo","age":"26","phone":"44444422","comments":""}]
can you please let me know how I can get rid of the []
at begiining and end of the JSON and have only
{"id":"1","name":"tabo","age":"26","phone":"44444422","comments":""}
at output? The reason that I need to do this is accessing the JSON object by using the jQuery.parseJSON()
which those []
make the properties undefined!
Thanks
You are putting an array into a variable and turning it into an array. The JSON encode is saying that the object is an array with the []
.
You can get past this by doing the encode right on the spot:
if($results) {
while($row = $results->fetch_assoc()) {
$json=json_encode($row);
}
}
$con->close();
echo $json;
The encoded JSON you are echoing is basically telling you that the object you encoded is an array with all the bits inside it. What you are trying to do is to show the $row
as a JSON, not the row inside an array.