Create json Object by php from mysql result [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JSON encode MySQL results
I want to use php to create a json object like below. it will return a string as a response from result sql query.
{"Orders":[
{"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"},
{"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"}
]
}
my code
<?php
mysql_connect("mysql12.000webhost.com","a4602996_longvan","longvan2012");
mysql_select_db("a4602996_lv");
$id=$_POST[user];
$sql=mysql_query("select * from testlongvan where Status = 'PACKED'" );
$json = array();
if(mysql_num_rows($sql)){
while($row=mysql_fetch_row($sql)){
$json['Orders'][]=$row;
}
}
//while($row=mysql_fetch_assoc($sql))
//$output[]=$row;
print(json_encode($json));
mysql_close();
?>
But when use my code the result is not what I expected:
{"Orders":[
["longvan","10/12/2012","Be34433jh","Long Van","115 Pham Viet Chanh, quan Binh Thanh","http://longvansolution.tk/image/sample.jpg","PACKED","0909056788"],
["takeshi","24/12/2012","BF6464633","Vn-zoom","16 nguyen cuu van, quan binh thanh","http://longvansolution.tk/image/hoadon3.jpg","PACKED","098897657"]
]}
Can you help me?

You have to create an array for each row to specify the field name and value.
$json['Orders'][] = array('DeliveryId' => $row[0], 'CustomerName' => $row[1], ...);
Or use mysqli_fetch_assoc() function if the table column name is exactly what you want to use in your JSON:
$rows = array();
while($r = mysqli_fetch_assoc($sql)) {
$rows[] = $r;
}
$data = array('Orders' => $rows);
print json_encode($data);

Related

Create php key and value array [duplicate]

This question already has answers here:
JSON encode MySQL results
(16 answers)
Closed 3 years ago.
I am trying to create a key and value array from database record, but the array just getting the final record! Here is a snippet of my code:
$cateogiresArr = array();
while ($row = mysqli_fetch_row($result))
{
$cateogiresArr["categoryname"] = $row[1];
$cateogiresArr["description"] = $row[2];
}
header("Content-type:application/json");
$json_categories = json_encode($cateogiresArr);
On each iteration add new array with required data to $cateogiresArr:
while ($row=mysqli_fetch_row($result))
{
$cateogiresArr[] = [
"cateogryname" => $row[1],
"description" => $row[2],
];
}

PHP Return Array in JSON , what happen this return include index? How To Fix? [duplicate]

This question already has answers here:
mysqli_fetch_array Gives Me Duplicate Rows
(4 answers)
Closed 3 years ago.
enter image description here
$table = $this->Execute("select * from data ");
$result = array();
while($row = mysqli_fetch_array($table))
{
array_push($result, $row);
}
return $result;
this my code,
i dont know why my result including the index
Its because of this statement:
while($row = mysqli_fetch_array($table))
You are getting numeric indexes as well as text keys.
Replace this by:
while($row = mysqli_fetch_assoc($table)) // will return only associate (string) keys.
OR
while($row = mysqli_fetch_array($table, MYSQLI_ASSOC)) // will return only associate (string) keys.
This will not include numeric indexes.
References:
mysqli_fetch_assoc()
mysqli_fetch_array()

json_encode doesn't display all array values [duplicate]

This question already has answers here:
php json_encode not working on arrays partially
(2 answers)
Closed 5 years ago.
I have a PHP script where it fetches all records from a table and encodes it to JSON. The table has a total of 246 records. echo count(); returns 246 as well.
The problem is, whenever I use json_encode, it doesn't display the values from the array at all, all I see is a blank page. But if I reduce the number of records to 13 instead of 246, it works and it displays the encoded JSON result. I have also tried to increase the memory_limit at my php.ini file to 4095M, but no avail.
$result = mysqli_query($con, "SELECT * FROM cities");
if (mysqli_num_rows($result) > 0) {
$response["cities"] = array();
$city = array();
while($row = mysqli_fetch_assoc($result)) {
$city[] = $row;
array_push($response["cities"], $city);
}
$response["success"] = 1;
echo json_encode($response);
}
Try below and you'll get to know what is happening exactly:
$json = json_encode($response);
if ($json)
echo $json;
else
echo json_last_error_msg();
json_last_error_msg() - Returns the error string of the last json_encode() or json_decode() call
Array "city" is expanding for each call and you are pushing the complete array on each iteration in loop .
Try :
while($row = mysqli_fetch_assoc($result)) {
array_push($response["cities"], $row);
}
It should work
Remove $response array push $row into $cities array. After pushing all city set the city and response in json_encode(); function like this echo json_encode(array("cities"=>$cities, "success"=>1));
if (mysqli_num_rows($result) > 0) {
$cities = array();
while($row = mysqli_fetch_assoc($result)) {
array_push($cities, $row);
}
echo json_encode(array("cities"=>$cities, "success"=>1));
}

If Array is Empty PHP - Highcharts [duplicate]

This question already has answers here:
How to check whether an array is empty using PHP?
(24 answers)
Closed 7 years ago.
I am creating a form to filter the data on my database (Mysql) with queries based on the user's selections.
I am using this code to generate the "data.json" file:
How can I improve the code and check if the array returns empty values? and instead of drawing a chart without bars tells the user to change the selections.
<?php
$rows1 = array();
$rows1['name'] = $varLabel;
while($rr = mysqli_fetch_array($TableData)) {
$rows1['data'][] = $rr[$varLabel];
}
$rows = array();
$rows['name'] = "Registros";
foreach($TableData as $r) {
settype($r['cnt'], "integer");
$rows['data'][] = $r['cnt'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
file_put_contents("data.json", json_encode($result));
?>
Since your array is created by looping over your database result set which you access using mysqli, Use mysqli_num_rows
if(mysqli_num_rows($TableData)==0)
{
// no data
}

Create an array from values from mysql table [duplicate]

This question already has answers here:
Creating an array from a MySQL table
(2 answers)
Closed 10 years ago.
I am using PHPlot to make a graph.
I have an issue in generating the array from a MySQL table.
Basivally, I want to array is as follows:
$values = array($arrayx);
array('a',-3),
array('b',5),
array('c',7),
array('d',8),
array('e',12),
array('f',-6),
//);
$graph->SetDataValues($values);
$graph->SetXTickPos('none');
$graph->SetXTickLabelPos('none');
Part of the code where I tried to retrieve values from table to feed the array
$query="SELECT * FROM tasks";
$result=mysql_query($query);
//using a for loop to add values to the array
while ($resource=mysql_fetch_array($result)){
$thedate = $resource["date"];
$title = $resource2["title"];
$innerarray = "array('.$thedate.', $title),";
}
$values = array($innerarray).");";
$graph->SetDataValues($values);
$graph->SetXTickPos('none');
$graph->SetXTickLabelPos('none');
//Draw it
$graph->DrawGraph();
}
The way I'm doing the $innerarray and $values seems wrong. Can you please help me fix it?
Thank you
try replacing
$innerarray = "array('.$thedate.', $title),";
with
$innerarray = array($thedate, $title);
$new = array();
while(for condition ){
$new[] = '\''.thedate[$i].''\','.$title[$i].'\';
}
var_dump($new);
this an idea, you need to edit the code to make it working
I assume it is this that you want:
$sql="SELECT datefield, titlefield FROM tasks";
....
while (list($thedate,$thetitle) = mysql_fetch_array($result)) {
$values[] = array($thedate,$thetitle);
}
echo $values[0][0]; // will output your 1st date
echo $values[0][1]; // will output your 1st title

Categories