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
));
Related
I have a bit of code I would like to pass through my json array that is not contained in the database $row. So i tried to set a custom variable and that didn't work. Is there a way to do this so the below content gets sent through with the array?
Here is what I tried
PHP
if ($photo_numff == 1) {
$streamitem_uploadimage_count =" Uploaded new image";
} else if($photo_numff > 1) {
$streamitem_uploadimage_count =" Uploaded ".$photo_numff." new images";
} else {
}
JSON array
$rowcount = mysqli_num_rows($result);
$json = array(
'posts' => array(),
'count' => $rowcount
);
while ($row = mysqli_fetch_array($result)) {
$posts[] = array(
//Post information and ids
'streamitem_id' => $row['streamitem_id'], // post id
'streamitem_uploadimage_count' => $streamitem_uploadimage_count,
);
$rowcount++;
}
$json['posts'] = $posts;
echo json_encode($json);
I can then take this through my ajax "+response['streamitem_uploadimage_count']+"
I have also tried array_push($json['posts'], array( 'streamitem_uploadimage_count' => $streamitem_uploadimage_count, ) );but doesn't work
I have now got this working by adding
'streamitem_uploadimage_count' => $streamitem_uploadimage_count
within the $Json array also.
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!
I have this php code that i need to change the JSON format i get the data from a mysql db:
// Retrieve data from database
$sql="SELECT nombre FROM deudores ORDER BY fecha ASC LIMIT 10";
$result=mysqli_query($con, $sql);
$emparray = array();
// Start looping rows in mysql database.
while($rows=mysqli_fetch_assoc($result)){
$emparray[] = $rows;
// close while loop
}
//print_r($emparray);
//echo json_encode($emparray);
$output = array(
'c2array' => true,
'size' => array(
0 => count($emparray),
1 => 1,
2 => 1
),
'data' => array()
);
$x = 0;
foreach ($emparray as $value) {
$output['data'][$x] = array();
$output['data'][$x][0] = array();
$output['data'][$x][0][0] = $value;
$x++;
}
echo json_encode($output);
That code print this JSON:
{"c2array":true,"size":[7,1,1],"data":[[[{"nombre":"test"}]],[[{"nombre":"Oscar"}]],[[{"nombre":"Oscar"}]],[[{"nombre":"test"}]],[[{"nombre":"test"}]],[[{"nombre":"oscar"}]],[[{"nombre":"Oscar"}]]]}
but i need the JSON to look like this:
{"c2array":true,"size":[7,1,1],"data":[[[test]],[[Oscar]],[[Oscar]],[[test]],[[test]],[[oscar]],[[Oscar]]]}
How can i achive this?
Thanks in advance!
Use mysql_fetch_row() instead of mysql_fetch_assoc.
while($rows=mysqli_fetch_row($result)){
$emparray[] = $rows;
// close while loop
}
And just set $emparray as value for $output['data']. No need extra work!
$output['data'] = $emparray;
This should make the output like this :
{"c2array":true,"size":[7,1,1],"data":[["test"],["Oscar"],["Oscar"],["test"],["test"],["oscar"],["Oscar"]]}
I am currently using a JSON encoded array to display the title in my database for an auto-suggest feature.
It looks something like this:
<?php
require_once('./includes/config.php');
require_once('./includes/skins.php');
mysql_connect($conf['host'], $conf['user'], $conf['pass']);
mysql_select_db($conf['name']);
$query2012 = sprintf("SELECT * FROM imdb WHERE poster !='posters/noposter.jpg' ORDER BY RAND() DESC LIMIT %d;", 8);
$result = mysql_query($query2012);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['title'] = $row['title'];
$row_array['year'] = $row['year'];
$row_array['poster'] = $row['poster'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
This returns:
[{"title":"The Woman","year":"2011","poster":"posters\/tt1714208.jpg"},{"title":"DeadHeads","year":"2011","poster":"posters\/tt1273207.jpg"},{"title":"The Innkeepers","year":"2011","poster":"posters\/tt1594562.jpg"},{"title":"John Carter","year":"2012","poster":"posters\/tt0401729.jpg"},{"title":"American Reunion","year":"2012","poster":"posters\/tt1605630.jpg"},{"title":"The Avengers","year":"2012","poster":"posters\/tt0848228.jpg"},{"title":"Chronicle","year":"2012","poster":"posters\/tt1706593.jpg"},{"title":"Big Miracle","year":"2012","poster":"posters\/tt1430615.jpg"}]
First, how would I manually add an additional object to this output? For example, let's say I wanted to add: {"status":"ok","message":"Success","data":
{"status":"ok","message":"Success","data":[{"title":"The Woman","year":"2011","poster":"posters\/tt1714208.jpg"},{"title":"DeadHeads","year":"2011","poster":"posters\/tt1273207.jpg"},{"title":"The Innkeepers","year":"2011","poster":"posters\/tt1594562.jpg"},{"title":"John Carter","year":"2012","poster":"posters\/tt0401729.jpg"},{"title":"American Reunion","year":"2012","poster":"posters\/tt1605630.jpg"},{"title":"The Avengers","year":"2012","poster":"posters\/tt0848228.jpg"},{"title":"Chronicle","year":"2012","poster":"posters\/tt1706593.jpg"},{"title":"Big Miracle","year":"2012","poster":"posters\/tt1430615.jpg"}]}
and if mysql record not found show json output
{"status":"error","message":"No Reord found"}
how i can add this ?
You can add this to your $json_response array before encoding (json_encode() by modifying it structute:
$json_response = array(
'data' => $json_response,
'status' => 'ok',
'message' => 'Successs'
);
You can also modify appending data to your final result variable so while you define your $json_response array add subarray:
$json_response = array('data' => array());
and in while loop add index data:
array_push($json_response['data'], $row_array);
And after loop you can easily append your status and message by:
$json_response['status'] = 'ok';
$json_response['message'] = 'Success';
To add error just check if the data array is empty. For first solution:
if (empty($json_response)) {
$json_response = array(
'status' => 'error',
'message' => 'No Reord found'
);
} else {
// here append success message
}
In second case just change a if condition to:
if (empty($json_response['data']))
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.