Hi I am trying to create an API that converts a results array from a database call into json that can be easily parsed.
Using the simple command json_encode, my JSON is a complicated, verbose mess of nested objects and arrays that is proving hard to parse on the other end.
Can anyone suggest a way to pare this down to the key information that should be provided: userid, long comment (lcom) and short comment (shcom) and how to send this as an API?
Thanks in advance for any suggestions
Here is the current JSON output produced from the following query and code:
$sql = "SELECT userid,shcom,lcom FROM comments WHERE userid = 1 LIMIT 4";
$res = mysql_query($sql) or die(mysql_error());
$comments = array();
while($row = mysql_fetch_array($res)) {
$comments[] = array('row'=>$row);
}
echo json_encode(array('comments'=>$comments));
Json output:
{
"comments": [
{
"row": {
"0": "1",
"userid": "1",
"1": "hello",
"shcom": "hello",
"2": "hellothere",
"lcom”: "hellothere"
}
},
{
"row": {
"0": "1",
"userid": "1",
“1”: ”agreed”,
"shcom”: ”agreed”,
“2”: ”agreedforonce”,
"lcom”: ”agreedforonce”
}
},
{
"row": {
"0": "1",
"userid": "1",
"1": "gohome",
"shcom”: ”gohome“,
“2”: ”gohomenow”,
"lcom: ”gohomenow”
}
},
{
"row": {
"0": "1",
"userid": "1",
"1": "getout”,
"shcom”: ”getout”,
“2”: ”getoutofhere”,
"lcom: ”getoutofhere”
}
}
]
}
You should be using mysqli rather than mysql since mysql is deprecated. Regardless, the problems in your code are happening because of two reasons. One, mysql_fetch_array does not produce the results you are expecting. Two, in your iteration you are not extracting the answers the right way. To resolve, use mysq_fetch_assoc and push only each $row to your final array.
Replace this:
while($row = mysql_fetch_array($res)) {
$comments[] = array('row'=>$row);
}
to this:
while($row = mysql_fetch_assoc($res)) {
$comments[] = $row;
}
Related
I'm new to php and am trying to encode 2 arrays together into one JSON object.
Currently this is the JSON output:
{
"image_link": "some url",
"zoomin_level": "8",
"zoomout_level": "18.5",
"position_lat": "32.913105",
"position_long": "-117.140363",
}
What I like to achieve is the following:
{
"image_link": "some url",
"zoomin_level": "2",
"zoomout_level": "15",
"position_lat": "32.9212",
"position_long": "-117.124",
"locations": {
"1": {
"image_link": "some url",
"name": "Name",
"lat": 32.222,
"marker_long": -112.222
},
"2": {
"image_link": "some url",
"name": "Name",
"lat": 32.222,
"marker_long": -112.222
}
}
}
This is similar to the question asked here: PHP json_encode multiple arrays into one object
However mine is a bit different because I like to add the 2nd array as part of a key-value part within the 1st array.
Here's my php code:
$sql = "select * from first_table";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$rowCount = $result->num_rows;
$index = 1 ;
$newArray = [];
while($row =mysqli_fetch_assoc($result))
{
$sqlnew = "select * from second_table";
$resultnew = mysqli_query($connection, $sqlnew) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$jsonData = array();
$rowCountnew = $resultnew->num_rows;
$indexnew = 1;
if ($rowCountnew >0)
{
while($rownew =mysqli_fetch_assoc($resultnew))
{
$locations[$indexnew] = array("image_link" => $rownew['image_link'], "name" => $rownew['name'], "position_lat" => doubleval($rownew['position_lat']), "position_long" => doubleval($rownew['position_long']) );
++$indexnew;
}
}
$newArray[$row['map_type']] = $row['map_value'];
}
echo json_encode($newArray);
Not knowing the proper syntax, I tried to perform the following which resulted in garbage: echo json_encode($newArray, "locations" =>$locations);
Try:
$newArray['locations'] = $locations;
echo json_encode ($newArray);
$result = $db->query($select_msgsum); //query the new msgsum table
//defining label that google needs
$col1 = array();
$col1["id"]="";
$col1["label"]="MessageType";
$Col1["pattern"]="";
$col1["type"]="string";
$col2 = array();
$col2["id"]="";
$col2["label"]="MessageCount";
$Col2["pattern"]="";
$col2["type"]="number";
// rows?
//filling the json data to it
while($data=$result->fetchArray()){
array_push($col1, $data['msg_type']);
array_push($col2, $data['msg_count']);
}
$cols = array($col1, $col2);
file_put_contents('../json/chart_data.json', json_encode($cols));
?>
The result i get is as following which is not accepted as explained here: https://developers.google.com/chart/interactive/docs/php_example
[
{
"0": "General question",
"1": "Job-fulltime",
"2": "Job-parttime",
"3": "Just Hello",
"id": "",
"label": "MessageType",
"type": "string"
},
{
"0": 6,
"1": 3,
"2": 9,
"3": 12,
"id": "",
"label": "MessageCount",
"type": "number"
}
]
you can directly convert the result from query to JSON.. try this ..
$result = $db->query($select_msgsum);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode($rows);
For a school project I have to display database data as a valid json file.
$result = mysqli_query($mysqli, "SELECT * FROM `csvdata`");
echo "{ \"films\" : [";
while ($row = mysqli_fetch_array($result)) {
$jsonResult = json_encode($row);
echo $jsonResult;
echo ",";
}
echo "]}";
The output i get is:
{
"films": [
{
"0": "Man on fire",
"titel": "Man on fire",
"1": "Actie",
"genre": "Actie"
},
{
"0": "Dumb and Dumberer",
"titel": "Dumb and Dumberer",
"1": "Comedy",
"genre": "Comedy"
},
{
"0": "DefQon 2014",
"titel": "DefQon 2014",
"1": "Muziek",
"genre": "Muziek"
},
]
}
Now my question is, how do I remove the last comma, I cannot find that. And all data tells the data 2 times, I also don't know how to avoid this.
Let json_encode handle the entire thing - build one array of data, and use json_encode on that.
$result = mysqli_query($mysqli, "SELECT * FROM `csvdata`");
$response = array();
$response['films'] = array();
while ($row = mysqli_fetch_array($result)) {
$response['films'][] = $row;
}
echo json_encode($response);
A good way to do this, is to not place a comma after writing every record, but instead before every record.
Then all you have to do, is add an if statement that doesn't output the comma for the very first row.
I'm playing with JSON using PHP. I'm using json_encode() function to create JSON. Hovewer I've got strange JSON output:
[
{
"0": "1",
"1": "test",
"2": "test",
"ID": "1",
"title": "test",
"imageUrl": "test"
},
{
"0": "2",
"1": "welcome",
"2": "http://overkiller.pl/Smokopedia/Images/01.jpg",
"ID": "2",
"title": "welcome",
"imageUrl": "http://overkiller.pl/Smokopedia/Images/01.jpg"
}
]
Why I am getting this sort JSON how to get rid these numbers from it?
My PHP code:
<?php
header('Content-type: application/json');
$connection = mysql_connect('localhost', 'root', 'sam1');
$array = array();
if($connection)
{
mysql_select_db("Smokopedia");
$result = mysql_query("Select * from mainMenu");
if($result)
{
while ($row = mysql_fetch_array($result))
{
array_push($array, $row);
}
echo json_encode($array);
}else
{
$errorJson = array(
message => 'Result is empty or incorrect',
type => 'error'
);
echo json_encode($errorJson);
}
}
mysql_close();
?>
mysql_fetch_array includes both numeric indexed keys and column name indexed keys.
Change it to mysql_fetch_assoc and you'll get the end result you need.
Note though, that the entire mysql extension is deprecated and you should consider switching to PDO or Mysqli.
The issue is you are fetching an array, which includes both numerical indexes and string keys.
Change to mysql_fetch_assoc
while ($row = mysql_fetch_ssoc($result))
Side note: the mysql_* library is deprecated. Considered upgrading to a modern API such as MySQLi or PDO.
I have developed an api which will post some data in json format to be used in an android app. However I am getting json parsing error. I am new to this whole json thing so unable to understand what the error means.
This is my json encoded output that the php backend generates
{
"data": [
{
"id": "2",
"name": "Rice",
"price": "120",
"description": "Plain Rice",
"image": "6990_abstract-photo-2.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
}
]
}{
"data": [
{
"id": "4",
"name": "Dal",
"price": "5",
"description": "dadadad",
"image": "",
"time": "20 mins",
"catagory": "Dinner",
"subcat": ""
}
]
}{
"data": [
"catagory": "Soup"
]
}
This is the error the online json parser gives
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 1 of the JSON data
What is actually wrong here? Could you please provide me with the correct json output for the following data?
This should clear it up
$main = array();
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'"; //Prepare login query
$value = $DBH->query($query1);
if($row1 = $value->fetch(PDO::FETCH_OBJ))
{
$main[] = array('data'=>array($row1));
}
else
{
$main[] = array('data'=>array('catagory'=>$row['category']));
}
}
echo json_encode($main);
You shouldn't create your json string by hand. Create your array structure, then finally invoke json_encode() at the end.
$data = array();
try
{
$query = "SELECT category FROM category"; // select category FROM category? what?
$result= $DBH->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'";
$value = $DBH->query($query1);
if($value->rowCount() > 0) {
$data[] = array('data' => $value->fetch(PDO::FETCH_ASSOC));
}
else {
$sub = array('category' => $row['category']);
$data[] = array('data' => $sub);
}
}
$result->closeCursor();
$DBH = null;
echo json_encode($data); // encode at the end
}
catch(PDOException $e)
{
print $e->getMessage ();
die();
}