Reputation: 103
i have a table named mobile in which all the mobile data is contained which have more then 7000 records now i want to display in json format but some how records are not showing here is my code kindly check ..
<?php
$conn = mysqli_connect("localhost","root","","test") or die ("Error ".mysqli_error($conn));
$sql = "select * from mobile";
$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
var_dump($result);
$myArray = array();
while($row = mysqli_fetch_assoc($result)){
$myArray[] = $row;
}
mysqli_close($conn);
header('Content-Type: application/json');
//$json = file_get_contents('json.json');
/*
$myArray = array("user1" => array("firstName" => "Mike2", "lastName" => "Smith" , "age" => 34),"user2" => array("firstName" => "Mike2", "lastName" => "Smith" , "age" => 34));
*/
$json = json_encode($myArray);
echo $json;
?>
table
Upvotes: 1
Views: 582
Reputation: 2968
The problem with JSON_ENCODE in PHP is, it tends to add double quotes and escaping sequences which would increase the actual size of the JSON being imported. So, please try this. This worked for me.
<?php
header('Content-Type: application/json');
$conn = mysqli_connect("localhost","root","","test") or die ("Error ".mysqli_error($conn));
$sql = "select * from mobile";
$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
$myArray = array();
while($row = mysqli_fetch_assoc($result)){
$myArray[] = $row;
}
mysqli_close($conn);
$prefix = '';
echo '[';
foreach($myArray as $row) {
echo $prefix, json_encode($row);
$prefix = ',';
}
echo ']';
?>
Upvotes: 1
Reputation: 999
You can do this by following way:
var obj = JSON.parse($myArray);
echo obj;
Upvotes: 0
Reputation: 6254
I assume you are probably using ajax to get your data in the browser you have used a var_dump()
in your php code followed by the json headers followed by the json result which will not work.
In order to set headers , the header()
function should be called first before printing out any other thing, also you do no need to put in the var dump. Try the following code:
<?php
$conn = mysqli_connect("localhost","root","","test") or die ("Error ".mysqli_error($conn));
$sql = "select * from mobile";
$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
$myArray = array();
while($row = mysqli_fetch_assoc($result)){
$myArray[] = $row;
}
mysqli_close($conn);
header('Content-Type: application/json');
$json = json_encode($myArray);
echo $json;
?>
Upvotes: 0