PHP JSON Array encoding for use with JSOUP Android - php

I am trying to build a catalog database that will interact with an Android Application for viewing when one scans a barcode. The app should ask the MySQL database and query for the various items associated with the part. Code is here for the MySQL part of it:
<?php
if(isset($_POST['submit']) || isset($_POST['catalog'])) {
require("connect_to_mysql.php");
header("content-type: application/json");
$tables_result = mysql_query("SHOW TABLES") or die(mysql_error());
while ($table = mysql_fetch_row($tables_result)) {
$query_results = mysql_query("SELECT * FROM ".$table[0]." WHERE catalog = '".$_POST['catalog']."'") or die(mysql_error());
if (mysql_num_rows($query_results) > 0) {
$fields = mysql_query("SHOW COLUMNS FROM ".$table[0]);
while ($res = mysql_fetch_array($fields)) {
$names[] = $res[0];
}
$comments = mysql_fetch_row(mysql_query("SELECT table_comment FROM INFORMATION_SCHEMA.TABLES WHERE table_name='".$table[0]."'")) or die(mysql_error());
while($array = mysql_fetch_array($query_results)){
$rows["part"] = $comments[0];
$rows["fields"] = $names;
for($i = 0; $i < mysql_num_fields($query_results); $i++){
$rows[$names[$i]] = $array[$i];
}
echo json_encode($rows);
}
}
}
mysql_free_result($tables_result);
}
if(!isset($_POST['submit']) || !isset($_POST['catalog'])) {
echo "
<form method='post'>
<input type='text' name='catalog' />
<input type='submit' name='submit' />
</form>
";
}
?>
However, for instance, a result of this would be:
{"part":"Lospa Tibial Baseplate","fields":["catalog","size"],"catalog":"01.10.50B","size":"11"}
I am using JSOUP on the Android Client Side and it has the function of returning a JSONArray. A JSONArray from when I've used this in the past looks like this (the part of the JSON I am having a problem with is the "field" object):
{"part":"Lospa Tibial Baseplate","fields":{["catalog","size"]},"catalog":"01.10.50B","size":"11"}
I've tried straight up encoding the array before encoding the fields array but that didn't work out and returned a bunch of slashes and useless stuff:
{"part":"Lospa Tibial Baseplate","fields":"[\"catalog\",\"size\"]","catalog":"01.10.50B","size":"11"}
What's the best way I should go about this? I would rather not just hard-code the two brackets into there, but if that is the last option, please show me how to do that because I can't just $rows["fields"] = "{".$names."}";

Try encoding the structure after it has finished building:
if(isset($_POST['submit']) || isset($_POST['catalog'])) {
require("connect_to_mysql.php");
header("content-type: application/json");
$tables_result = mysql_query("SHOW TABLES") or die(mysql_error());
while ($table = mysql_fetch_row($tables_result)) {
$query_results = mysql_query("SELECT * FROM ".$table[0]." WHERE catalog = '".$_POST['catalog']."'") or die(mysql_error());
if (mysql_num_rows($query_results) > 0) {
$fields = mysql_query("SHOW COLUMNS FROM ".$table[0]);
while ($res = mysql_fetch_array($fields)) {
$names[] = $res[0];
}
$comments = mysql_fetch_row(mysql_query("SELECT table_comment FROM INFORMATION_SCHEMA.TABLES WHERE table_name='".$table[0]."'")) or die(mysql_error());
while($array = mysql_fetch_array($query_results)){
$rows["part"] = $comments[0];
$rows["fields"] = $names;
for($i = 0; $i < mysql_num_fields($query_results); $i++){
$rows[$names[$i]] = $array[$i];
}
}
// JSON encode at the end
echo json_encode($rows);
}
}
mysql_free_result($tables_result);
}
This is invalid JSON, by the way:
{"fields":{["catalog","size"]},"catalog":"01.10.50B","size":"11"}
Should be more like this if fields must be an object.
{"fields":{"key":["catalog","size"]},"catalog":"01.10.50B","size":"11"}
So it's better to check if your JSOUP parsing is setup correctly.

I figured it out. Here is my code below. I basically had to make an array of encoded JSON objects. Thanks to Kim for pointing in the right direction. I also did some changes the the function, but that doesn't have an impact on the JSON Part of it.
<?php
if(isset($_POST['catalog'])) {
require("connect_to_mysql.php");
header("content-type: application/json");
$tables_result = mysql_query("SHOW TABLES") or die(mysql_error());
while ($table = mysql_fetch_row($tables_result)) {
$query_results = mysql_query("SELECT * FROM ".$table[0]." WHERE catalog = '".$_POST['catalog']."'") or die(mysql_error());
if (mysql_num_rows($query_results) > 0) {
$comments = mysql_fetch_row(mysql_query("SELECT table_comment FROM INFORMATION_SCHEMA.TABLES WHERE table_name='".$table[0]."'")) or die(mysql_error());
$columns_sql = mysql_query("SELECT COLUMN_COMMENT FROM information_schema.COLUMNS WHERE TABLE_NAME = '".$table[0]."'") or die(mysql_error());
$rows["validity"] = true;
$rows["part"] = $comments[0];
while ($res = mysql_fetch_array($columns_sql)) {
$names[] = $res[0];
}
$rows["fields_count"] = count($names);
while($array = mysql_fetch_array($query_results)){
for($i = 0; $i < mysql_num_fields($query_results); $i++){
$values[] = array($names[$i] => $array[$i]);
}
}
$rows["fields"] = $values;
echo json_encode($rows);
exit();
}
}
echo '{"validity":false}';
mysql_free_result($tables_result);
}
?>

The field structure is not correct...
This is why I use the Simple JSON for PHP library! It allows to avoid to hardcode our JSON.
Using $Json->addContent(new arrayJson("fields",$values)); will set the field fields of your json equals to your values. It should look like this :
<?php
include('includes/json.php');
$Json = new json();
if(isset($_POST['catalog'])) {
require("connect_to_mysql.php");
header("content-type: application/json");
$tables_result = mysql_query("SHOW TABLES") or die(mysql_error());
while ($table = mysql_fetch_row($tables_result)) {
$query_results = mysql_query("SELECT * FROM ".$table[0]." WHERE catalog = '".$_POST['catalog']."'") or die(mysql_error());
if (mysql_num_rows($query_results) > 0) {
$comments = mysql_fetch_row(mysql_query("SELECT table_comment FROM INFORMATION_SCHEMA.TABLES WHERE table_name='".$table[0]."'")) or die(mysql_error());
$columns_sql = mysql_query("SELECT COLUMN_COMMENT FROM information_schema.COLUMNS WHERE TABLE_NAME = '".$table[0]."'") or die(mysql_error());
$Json->addContent(new propertyJson('status', '200'));
$Json->addContent(new propertyJson('validity', true));
$Json->addContent(new propertyJson('part', $comments[0]));
while ($res = mysql_fetch_array($columns_sql)) {
$names[] = $res[0];
}
$Json->addContent(new propertyJson('count', count($names))); =
while($array = mysql_fetch_array($query_results)){
for($i = 0; $i < mysql_num_fields($query_results); $i++){
$values[] = array($names[$i] => $array[$i]);
}
}
$Json->addContent(new arrayJson("fields",$values));
json_send($Json);
exit();
}
}
$Json->addContent(new propertyJson('status', '200'));
$Json->addContent(new propertyJson('message', 'Validity failed'));
json_send($Json);
mysql_free_result($tables_result);
}
?>

Related

JSON encoding not working

Here is my code to encode data in JSON format, but it doesn't work. The result is []. Where is my mistake?
<?php
$conn = new mysqli('localhost','root','','project');
$data =array();
if(!empty($_GET['masp'])){
$masp =$_GET['masp'];
$sql ="SELECT *FROM sanpham WHERE masp='$masp'";
$result = mysqli_query($conn,$sql);
if($result){
while($r = mysqli_fetch_assoc($result)){
$r['masp'] =$data['masp'];
$r['loai'] =$data['loai'];
$r['hangsx']=$data['hangsx'];
$r['tensp']=$data['tensp'];
$r['img']=$data['img'];
$r['gia']=$data['gia'];
$r['nx']=$data['nx'];
}
}
}
print json_encode($data);
?>
You are setting your variables wrong.
In every while cycle you get a new $r variable that you want to add to your $data variable.
$conn = new mysqli('localhost', 'root', '', 'project');
$data = array();
if (!empty($_GET['masp'])) {
$masp = $_GET['masp'];
$sql = "SELECT *FROM sanpham WHERE masp='$masp'";
$result = mysqli_query($conn, $sql);
$i = 0;
if ($result) {
while ($r = mysqli_fetch_assoc($result)) {
$data[$i]['masp'] = $r['masp'];
$data[$i]['loai'] = $r['loai'];
$data[$i]['hangsx'] = $r['hangsx']];
$data[$i]['tensp'] = $r['tensp'];
$data[$i]['img'] = $r['img'];
$data[$i]['gia'] = $r['gia'];
$data[$i]['nx'] = $r['nx'];
$i += 1;
}
}
}
print json_encode($data);
You make mistake. You should swap variable data with r inner loop, but probably than also will works unpropely. write in while loop $data [] = $r;

php and mysql issue with query return

I have this code working but only halfway, it is able to return all of the information that I need however on the return, one of the JSON array is returned twice, why is this? I can't seem to figure out why.
Here is my code:
$rows = mysql_num_rows($res);
$array = array();
$i = 0;
while($row = mysql_fetch_array($res, MYSQL_NUM)) {
$array[$i] = (int)$row[0] . "\n";
$i++;
if ($i > $rows){
break;
}
}
$JsonArray = array();
for($i = 0; $i < $rows; $i++){
$q = "SELECT firstName, lastName, email from $mysql_database.$UsersTable WHERE idUser = $array[$i]";
$res = mysql_query($q, $connect) or die(mysql_error());
while($row = mysql_fetch_assoc($res)){
$new_array[] = $row; // Inside while loop
}
$JsonArray[$i] = $new_array;
}
echo json_encode($JsonArray);
This is the result:
All I need is the second and third but somehow I don't know why it is outputting the first twice.
Also, how can I format the result better in the JsonArray?
From what I see you are trying to do, you are trying to fetch your result set from the database for the query.
You need not make use of all those loops. All you have to do is:
$q = "SELECT firstName,lastName,email from $mysql_database.$UsersTable WHERE idUser=$array[$i]";
$res = mysql_query($q,$connect) or die(mysql_error());
$new_array = mysqli_fetch_assoc($res);
mysqli_free_result($res);
You do not need that while loop for each row.

how to encode json from array push?

i had this php code :
<?php
include "../mainmenu/koneksi.php";
// Start with the list of animals
$sql = "SELECT * FROM data_binatang";
$rows = array();
$res = mysql_query($sql);
for($i=0; $i<mysql_num_rows($res); ++$i){
$row1 = mysql_fetch_assoc($res);
$id_binatang = $row1['id_binatang'];
$sql = "SELECT * FROM data_waktu_vaksinasi WHERE id_binatang = $id_binatang AND (status_vaksin = 'belum' OR status_vaksin IS NULL) ORDER BY tanggal_vaksin ASC LIMIT 1";
$res2 = mysql_query($sql);
$row2 = mysql_fetch_assoc($res2);
$arr[$id_binatang] = array();
array_push($arr[$id_binatang], $row1['nama_binatang'], $row1['id_user'], $row1['jenis_binatang'], $row1['ras_binatang'], $row1['foto_binatang'], $row2['nama_vaksin'], $row2['id_data_waktu_vaksinasi'], $row2['status_vaksin'], $row2['tanggal_vaksin'], $row2['tanggal_datang']);
}
echo "RESULT:";
echo "<table border=1><tr><th>id binatang</th><th>nama binatang</th><th>id user</th><th>jenis binatang</th><th>ras binatang</th><th>foto binatang</th><th>nama vaksin</th><th>id data waktu vaksin</th><th>status vaksin</th><th>tanggal vaksin</th><th>tanggal datang</th></tr>";
foreach($arr as $key => $val){
echo "<tr><td>$key</td><td>".implode("</td><td>", $val)."</td></tr><br>";
}
?>
and here's the result
now i want to generate the table into json, but i don't know what to put inside the json encode, i tried:
echo '{"data_vaksinasi_menu":'.json_encode($arr[$id_binatang]).'}';
but instead it gave me null
Try this:
echo json_encode(array('data_vaksinasi_menu' => $arr));

Convert mysql select results to json (array of arrays)

I need to encode a table content to JSON in order to insert it into a file.
The output has to be as following :
{
"name1":[{"id":"11","name":"name1","k1":"foo","k2":"bar"}],
"name2":[{"id":"12","name":"name2","k1":"foo","k2":"bar"}],
}
Indeed, each JSON "line" corresponds to the content of the mysql row and the name of each JSON array is the name of the 'name' column.
The only thing I could manage for the moment is this :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
$index = 0;
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$index] = $row;
$index++;
}
echo json_encode($return_arr);
And here is the output I get :
[
{"id":"11","name":"name1","k1":"foo","k2":"bar"},
{"id":"12","name":"name2","k1":"foo","k2":"bar"},
]
Thanks a lot !!!
UPDATED
Working code :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$return_arr[ $row['nom_appart'] ][] = $row;
}
echo json_encode($return_arr);
}
You were close. I noticed you want final output to be an object not an array, because the outer brackets are {} not []. So you need a different object type, and you need to use each row's name as the key for storing that row.
$return_obj = new stdClass();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$name = $row['name'];
$return_obj->$name = [$row]; // for PHP < 5.4 use array($row)
}
echo json_encode($return_obj);
This loop is enough, to create the desired JSON:
$return_arr = array();
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$row['name']][] = $row; #or $return_arr[$row['name']] = [$row];
}
echo json_encode($return_arr);
I was working on it a lot of time and Create mash/mysql-json-serializer package.
https://github.com/AndreyMashukov/mysql-json-serializer
You can select Json_array of json_objects and etc. It support ManyToMany, oneToMany, manyToOne relations
SELECT JSON_ARRAYAGG(JSON_OBJECT('id',est_res.est_id,'name',est_res.est_name,'advert_groups',(SELECT JSON_ARRAYAGG(JSON_OBJECT('id',adg.adg_id,'name',adg.adg_name)) FROM advert_group adg INNER JOIN estate est_2 ON est_2.est_id = adg.adg_estate WHERE est_2.est_id = est_res.est_id))) FROM (SELECT * FROM estate est LIMIT 1 OFFSET 2) est_res
<?php
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$return_arr[] = $row;
}
echo json_encode($return_arr);
?>

Issue with php 2D array

i would like to store data from a form into 2D array
but it seems to have problem inserting data into the array.
if i were to echo $orderArray[0][$count2] it seems to work
but if i were to echo $orderArray[1][$count2] there will be error
$dateArray = array();
$orderArray = array(array());
$amountArray = array(array());
$count = 0;
$count2 = 0;
foreach ($_POST['export'] as $date){
$dateArray[$count] = $date;
include "/storescript/connect_to_mysql.php";
$sql = mysql_query("SELECT * FROM ordera WHERE orderDate = '$date' ORDER BY orderid ASC");
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysql_fetch_array($sql)){
$orderArray[$count][$count2] = $row["orderAmount"];
$amountArray[$count][$count2] = $row["itemAmount"];
$count2++;
}
}
$count++;
}
I would reduce the code to this:
// connect here
include "/storescript/connect_to_mysql.php";
// make date list safe for querying
$dates = join(',', array_map(function($date) {
return sprintf("'%s'", mysql_real_escape_string($date));
}, $_POST['export']);
// run query
$sql = "SELECT * FROM ordera WHERE orderDate IN ($dates) ORDER BY orderid";
$res = mysql_query($sql) or die("Error in query");
// collect results
while ($row = mysql_fetch_array($res)) {
$orders[$date][] = $row['orderAmount'];
$amounts[$date][] = $row['itemAmount'];
}
// do stuff with results
foreach ($orders as $date => $orderAmounts) {
print_r($orderAmounts);
print_r($amounts[$date]);
}
Also, please learn about PDO or mysqli; the old mysql_ functions are deprecated.

Categories