Get specific JSON data from sql query using PHP - php

I would like to say thank you for reading this question.
And my question is. I have this php code with sql query:
mysql_connect($mysql_server, $mysql_login, $mysql_password);
mysql_select_db($mysql_database);
$req = "SELECT name, elements "
."FROM lwzax_zoo_item "
."WHERE application_id = '2' AND elements LIKE '%".$_REQUEST['term']."%' ";
$query = mysql_query($req);
while($row = mysql_fetch_array($query))
{
$results[] = array('label' => $row['name'], 'desc' => $row['elements']);
}
$json = json_encode($results);
echo $json;
And output is:
[
{
"label":"0146T",
"desc":" {\n\t\"cec36dd6-ffde-494d-b25c-8e58bff84e22\": {\n\t\t\"0\": {\n\t\t\t\"value\": \"Ccta W\\/Wo Dye\"\n\t\t}\n\t}\n}"
},
{
"label":"64653",
"desc":" {\n\t\"cec36dd6-ffde-494d-b25c-8e58bff84e22\": {\n\t\t\"0\": {\n\t\t\t\"value\": \"Chemodenervation Eccrine Glands Oth Area Per Day\"\n\t\t}\n\t}\n}"
}
]
But I need only label data and value data...so it should look like:
[
{
"label":"0146T",
"desc":"Ccta W\\/Wo Dye"
},
{
"label":"64653",
"desc":"Chemodenervation Eccrine Glands Oth Area Per Day"
}
]
Could you please help me?
Thank you very much for help
UPDATE: Deleted $b = json_decode($row['desc'], true); as it wasn't used, just a junk from all my attempts to succeed.

You're decoding the JSON and assigning it to $b, but you're not doing anything with that variable. Use:
$results[] = array('label' => $row['name'],
'desc' => $b['cec36dd6-ffde-494d-b25c-8e58bff84e22'][0]['value']);
Also, you need to give a second argument to json_decode, so it will return an associative array rather than an object.
$b = json_decode($row['elements'], true);

OK, well, first things first, initialize your array OUTSIDE your loop.
while($row = mysql_fetch_array($query))
{
$b = json_decode($row['elements']);
$results[] = array('label' => $row['name'], 'desc' => $row['elements']);
}
Then you should probably do this:
$results = array();
while($row = mysql_fetch_array($query))
{
$b = json_decode($row['elements']);
array_push($results, array('label' => $row['name'], 'desc' => json_decode($row['elements'], true));
}
The at the end
$json = json_encode($results);
echo $json;
See if that helps.

Related

Convert PHP array from mysql to JSON format

I'm trying to convert the result array from Mysql to JSON format, the format doesn't seems to be correct, a comma is missing between each object. Please advice, thank you.
I'm aware that im using the deprecated version of php here.
$result = mysql_query("SELECT * FROM patientvaccinedetail")or
die(mysql_error());
while($row = mysql_fetch_array( $result,MYSQL_ASSOC)) {
$specific = ["message" => $row["message"],
"mobile" => $row["mobile"]];
print_r (json_encode($specific));
}
Current Result:
{"message":"hello","mobile":"12345678"}{"message":"hi","mobile":"87878965"}
Desired Result:
{"message":"hello","mobile":"12345678"}, {"message":"hi","mobile":"87878965"}
You have to use array and at end of loop you have to echo result
$specific = array();
while($row = mysql_fetch_array( $result,MYSQL_ASSOC)) {
$specific[] = ["message" => $row["message"],
"mobile" => $row["mobile"]];
}
echo json_encode($specific);
Please moved json_encode() to outside of while loop.
$specific = array();
while($row = mysql_fetch_array( $result,MYSQL_ASSOC)) {
$specific = ["message" => $row["message"],
"mobile" => $row["mobile"]];
}
print_r(json_encode($specific));

How to json encode a single object as a json objects array using PHP

For two objects:
{"publications":[{"nom":"toto","id":"2029","userid":"22","publication":"bla bla bla","time":"2017-02-20 00:00:00","avatar":{}},{"nom":"xxxx","id":"2027","userid":"31","publication":"kjdsfkuds","time":"2017-02-20 00:00:00","avatar":{}}]}
For One object:
{"publications":{"nom":"xxxx","id":"2027","userid":"31","publication":"kjdsfkuds","time":"2017-02-20 00:00:00","avatar":{}}}
i want to have always a json array as a return no matter how the number of objects.
PHP Code:
$result = $conn->query($sql);
$json = new SimpleXMLElement('<xml/>');
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$mydata = $json->addChild('publications');
$mydata->addChild('nom',$row['nom']);
$mydata->addChild('id',$row['id']);
$mydata->addChild('userid',$row['userid']);
/*echo(utf8_encode($row['publication']));*/
$mydata->addChild('publication',utf8_encode($row['publication']));
$mydata->addChild('time',$row['time']);
$mydata->addChild('avatar',$row['avatar']);
}
echo( json_encode ($json));
} else {
echo "0";
}
Well you are not using XML for anything else but convert it to JSON, so there is no need for XML. Use array
$result = $conn->query($sql);
$json = ['publications' => []];
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$json['publications'][] = [
'nom' => $row['nom'],
'id' => $row['id'],
'userid' => $row['userid'],
'publication' => $row['publication'],
'time' => $row['time'],
'avatar' => $row['avatar']
];
}
echo json_encode($json);
}
else
{
echo "0";
}
It's a particluar behaviour of SimpleXML.
If you have one child in xml - you will have an object in json, if you have more than one child - you will get array of objects. So, I advise you to rewrite your code using simple arrays instead of xml-approach:
$result = $conn->query($sql);
$json = []; // just array
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// add new item
$json[] = $row;
// or more specifically
$json[] = [
'nom' => $row['nom'],
'id' => $row['id'],
// more fields that you need
];
}
}
echo json_encode(['publications' => $json]);

How to make a JSON output like this?

My desired output
{"rowcount":4
[{"provider_id":"1","provider_name":"Crecent Computers","sub_name":["Hardware","Software","Networks"]}],[{"provider_id":"4","provider_name":"Testing Co. LLC","sub_name":["Hardware","Software","Networks"]}],[{"provider_id":"41","provider_name":"Itiology","sub_name":["Hardware","Software","Networks","All IT Services"]}],[{"provider_id":"42","provider_name":"ITiology","sub_name":["Hardware","Software","Networks","All IT Services","Website Design "]}]}
My desired output end
My current JSON output
{"rowcount":4,"0":[{"provider_id":"1","provider_name":"Crecent Computers","sub_name":["Hardware","Software","Networks"]}],"1":[{"provider_id":"4","provider_name":"Testing Co. LLC","sub_name":["Hardware","Software","Networks"]}],"2":[{"provider_id":"41","provider_name":"Itiology","sub_name":["Hardware","Software","Networks","All IT Services"]}],"3":[{"provider_id":"42","provider_name":"ITiology","sub_name":["Hardware","Software","Networks","All IT Services","Website Design "]}]}
JSON Output end
PHP CODE
$result = mysqli_query($con, "select * from service_provider where servicecategory_id = '1'");
if ($counter = mysqli_query($con, "select * from service_provider where servicecategory_id = '1'"))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($counter);
// Free result set
mysqli_free_result($counter);
}
$data_points = array();
$subcatArray = array();
$data_points["rowcount"] = $rowcount;
while($row = mysqli_fetch_assoc($result))
{
$subcatresult = mysqli_query($con, "SELECT sub_name, price FROM sub_services WHERE provider_id = " . $row['provider_id']);
while($subcatrow = mysqli_fetch_assoc( $subcatresult))
{
$subcatArray[] = $subcatrow['sub_name'];
unset($subcatrow);
$subcatrow = array();
}
$data_points[][] = [
'provider_id' => $row['provider_id'],
'provider_name' => $row['provider_name'],
'sub_name' => $subcatArray
];
// array_push("totalRow",$data_points, $point);
}
echo json_encode($data_points);
PHP CODE END
you desired output json is an invalid json. you can check this json out valid or not in the http://jsonviewer.stack.hu. json or xml has it's own patterns.
So i found out that my desired output is invalid. Sorry I'm new to PHP.
I removed this line
$data_points["rowcount"] = $rowcount;
and made this
$data_points[][] = [
'provider_id' => $row['provider_id'],
'provider_name' => $row['provider_name'],
'sub_name' => $subcatArray
];
into this
$data_points["Rows"][] = [
'provider_id' => $row['provider_id'],
'provider_name' => $row['provider_name'],
'sub_name' => $subcatArray
];
I got the output pretty much close to what i need. Thanks guys!

When using preg_replace on a variable in an array, the variable doesn't reflect preg_replace changes

I can't figure out what in the world is going wrong with my code.
Problem:
I'm getting results from a mysql DB, one of the variables returned needs to be run through preg_replace, the preg_replace() works just fine when I echo it out, but when I try to put that variable into the array, it doesn't reflect the preg_replace() changes.
$bl = array(
'skills' => array()
);
if ($result = $db->query($queryStmt)) {
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$newdesc = preg_replace("/\<[^>]+\)/","",$Desc);
$sk = array(
'desc' => $newdesc
);
array_push($bl['skills'], $sk);
}
};
header('Content-type: application/json');
echo json_encode($bl, JSON_NUMERIC_CHECK);
$db = NULL;
So again, if I echo the $newdesc variable before the array code, it displays properly, but when the array is echo'd out at the end of the script, it doesn't.
Edit:
Someone requested the echo response, if I echo out $newdesc this string:
MP Regeneration 3 Bow skills used at every blow mentality may be eligible for as much as 3 each additional (but does not apply to a range type)
simply echos out as this:
MP Regeneration 3 Bow skills used at every blow mentality may be eligible for as much as 3 each additional (but does not apply to a range type)
And the code now reflects this:
$bl = array(
'skills' => array()
);
if ($result = $db->query($queryStmt)) {
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$newdesc = preg_replace("/\<[^>]+\)/","",$Desc);
echo $newdesc;
$sk = array(
'desc' => $newdesc
);
array_push($bl['skills'], $sk);
}
};
header('Content-type: application/json');
echo json_encode($bl, JSON_NUMERIC_CHECK);
$db = NULL;
Edit again:
See answer for solution!
Thanks to the wonderful people in the comments, the solution to the problem was simply to use strip_tags() this my friends is a fine case of me being an idiot. Code is now this:
$bl = array(
'skills' => array()
);
if ($result = $db->query($queryStmt)) {
while ($row = mysqli_fetch_assoc($result)) {
$newdesc = strip_tags($row['Desc']);
$sk = array(
'desc' => $newdesc
);
array_push($bl['skills'], $sk);
}
};
header('Content-type: application/json');
echo json_encode($bl, JSON_NUMERIC_CHECK);
$db = NULL;
And it works perfectly.
I was making a function that already existed, read the documentation on strip_tags() for more info.
http://php.net/manual/es/function.strip-tags.php

Pulling data from MySQL into json array

I'm trying to pull data from my database using json in php. I have a few elements I need to specific then to post them on a page.
I want to "fetch" the data from mysql and return it to a json_encode. How can I do this using the SELECT method. Some had used PDO methods and other have used mysql_assoc, which confuses me.
For instance,
I have rows of: 'id' , 'title' , 'start', 'backgroundColor'...etc. along with a default value for all of them. ($array[] = "someValue = default")
I want it to export like so:
array(
'id' => 1,
'title' => "someTitle",
'start' => "2012-04-16",
'backgroundColor' => "blue",
'someValue' = > "default",
...
), ....
));
If anyone could help me with this with the best detail, I'd be awesome!
If you wanted to do this with PDO then here is an example:
<?php
$dbh = new PDO("mysql:host=localhost;dbname=DBNAME", $username, $password);
$sql = "SELECT `id`, `title`, `time`, `start`, `backgroundColor`
FROM my_table";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
//To output as-is json data result
//header('Content-type: application/json');
//echo json_encode($result);
//Or if you need to edit/manipulate the result before output
$return = [];
foreach ($result as $row) {
$return[] = [
'id' => $row['id'],
'title' => $row['title'],
'start' => $row['start'].' '.$row['time'],
'backgroundColor' => $row['backgroundColor']
];
}
$dbh = null;
header('Content-type: application/json');
echo json_encode($return);
?>
You don't "fetch to a json array".
You fetch your database results into a PHP array, then convert that php array, AFTER THE FETCHING IS COMPLETED, to a json string.
e.g.
$data = array();
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
echo json_encode($data);
You can get the result from mysql,then format it to json
$array = array();
while($row = mysqli_fetch_array($result))
{
array_push($array,$row);
}
$json_array = json_encode($array);
Please check for SELECT methods here
In general it would look like this
$data = array(); // result variable
$i=0
$query = "SELECT id,title,start,backgroundColor FROM my_table"; // query with SELECT
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){ // iterate over results
$data['item'][$i]['id'] = $row['id']; // rest similarly
...
...
$i++;
}
header('Content-type: application/json'); // display result JSON format
echo json_encode(array(
'success' => true,
'data' => $data // this is your data variable
));

Categories