Need to print mysql data in to json in a format - php

I am trying to get mysql data in to json using php and later access it in url. I am getting data in json but i need in a format. Below is my php code to get json.
header('Content-Type: application/json');
include('dbhconfig.inc.php');
$response = array();
$stmt = $dbh->prepare("SELECT * FROM venderlist");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
{
$response['results'] = $rows;
}
echo json_encode($response);
And my json data showing as bellow
{"results":[{"id":"1","vendname":"Genie Events","address":"15, Lower Ground Floor, Lajpat Nagar, Delhi - 110024, Near National Park ","contact":"(91)-11-33437065","contact_o":"(91)-11-40666522","est":"2010","website":"www.genieevents.com","email":"","zip":"110024","latitude":"1.28525","longitude":"103.775464","latlon":"1.28525,103.775464","type":"organisers"},
First of all its not showing in proper structure. And presently latlon is showing like "latlon":"1.28525,103.775464" but i want result should be "latlon":[1.28525,103.775464]
How to add [] to my json variable name latlon.

If course, you'll need to break down that part of the data first since its a string. You'll need to set them up as an array unit with both float values inside.
After fetching them all, you'll need to make a little bit of operations.
You can use explode on that string first with that ,. So that becomes an array []. But it doesn't end there, the exploded elements are still strings, so you can map out all elements with floatval with the use of arrray_map.
So all in all, it would look just like this:
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as &$r) { // with reference
// explode with comma, map with floatval
$r['latlon'] = array_map('floatval', explode(',', $r['latlon']));
}
echo json_encode(array('results' => $rows)); // json encode

Related

Pushing data to a JSON generated with json_encode

In the following lines everything works if I don't try to push something to $dataJson.
$reponse = $bdd->query("SELECT Comp_Name,Comp_Email
FROM Company");
while ($donnees = $reponse->fetchAll(PDO::FETCH_ASSOC)) {
$dataJson = json_encode($donnees);
$dataJson.push({Col1:'Company Name',Col2:'Email'});
echo $dataJson;
};
I want to add a last object to the array of object generated by json_encode.
I may be missing something easy since every tips I found on internet failed to solve my issue.
Thanks
First, you don't need to call fetchAll() in a loop. It fetches all the results at once.
Next, you seem to be mixing Javascript syntax into your PHP. PHP doesn't use .shift() to add to an array, or {} as syntax for objects.
Next, you don't push onto the JSON, you push onto the array, then you encode the array as JSON.
If you want the column headings to be at the beginning of the array, you should use array_unshift(), not array_push().
So it should be:
$donnees = $response->fetchAll(PDO::FETCH_ASSOC);
array_unshift($donnees, array('Col1' => 'Company Name', 'Col2' => 'Email'));
$dataJson = json_encode($donnees);
echo $dataJson;
json_encode converts an array into a string. You can't push anything to strings, and you you try to concatenate, you will not end up with invalid json. do this instead.
$reponse = $bdd->query("SELECT Comp_Name,Comp_Email
FROM Company");
$data=array();
while ($donnees = $reponse->fetch(PDO::FETCH_ASSOC)) {
$data[]=$donnees;
};
echo json_encode($data);

Convert JSON string from database to PHP array problems

I am trying to convert this JSON string into a PHP array. The JSON string is stored in my database and I have already retrieved it.
{
"users": "user1, user2"
}
I need to convert the above JSON string into an array like the following but dynamically.
$myArray = array("user1", "user2")
This is my code:
$row = mysqli_fetch_array($result);
$json = $row['json'];
$decode = json_decode($json);
$list = $decode->users;
$myArray = explode(',', $list);
This code doesn't work in my program but when I print the array with print_r it looks identical to if I print $myArray from the nondynamic string. This is a concern because the nondynamic string works.
The separator between the usernames is comma+space, you're just using comma when you explode, so the second and following usernames are getting a space at the beginning. Try:
$myArray = explode(', ', $list);
I recommend that you change the JSON structure so you store an actual array, rather than a comma-separated list.
{
"users": ["user1", "user2"]
}
Even better would be to change your database structure so the users are in a real table, rather than being wrapped in JSON. This would allow you to perform queries that search for users easily and efficiently.

PHP PDO retrieving json array from database - removing unwanted chars

I am storing a JSON array of data within a row in a database and attempting to retrieve the array in order to use in a foreach loop.
The code below is the code that I will be using for the foreach loop, but I am having some troubles actually retrieving the data, using PDO, as needed to be used.
$data = '[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]';
$array = json_decode($data, true);
foreach($array as $data){
echo $data['id'];
}
The problem I am having is retrieving the array to put into $data using PDO. Currently I have this query and code, the output for which is below.
$statement = $this->db_connection->prepare("SELECT gp FROM gs WHERE c_s= :c_s");
$statement->bindParam(':c_s', $c_s);
$statement->execute();
$data = $statement->fetchAll();
$result = json_encode($data, true);
return $result;
Mixed with the following code to show the array:
foreach ($result as $key) {
echo $key['id'];
}
print_r($result);
die();
This gives an error for the for each, and outputs the array (unusable) as following:
[{"gp":"[{\"id\":\"H592736029375\"},{\"id\":\"K235098273598\"},{\"id\":\"B039571208517\"}]","0":"[{\"id\":\"H592736029375\"},{\"id\":\"K235098273598\"},{\"id\":\"B039571208517\"}]"}]
Being as the first segment of code I have I can use the data as I needed I'm just in need of some guidance of how to correctly get the array from the database to then be used in the foreach.
I'm aware that I'm currently using json_encode instead of json_decode, using json_decode gives the following error:
Warning: json_decode() expects parameter 1 to be string, array given
Suggestions for my errors would be much appreciated
fetchAll() returns an array of rows, not the single field you expect:
$statement = $this->db_connection->prepare("SELECT gp FROM gs WHERE c_s= :c_s");
$statement->bindParam(':c_s', $c_s);
$statement->execute();
$rows = $statement->fetchAll();
$data = $rows[0]['gp'];
$result = json_decode($data);
You are expecting $data to be a string while it's an array. Either use $statement->fetchColumn() to retreive a single field or use json_decode($data['gp'])
Other then that, I'm not exactly sure why you are looping over a json_encoded array, you can't do that.
json_encode() formats variables for javascript object notation.
json_decode() loads variables from strings(READ: string, not array) in the javascript object notation.
To make it even clearer:
use json_encode() to insert data in mysql.
use json_decode() to put back a column to their corresponding php variable/state.

Serialized multidimensional stored in MySQLi does not print past first array

Confusing title, the basics are that I'm saving a fully sorted and ordered multidimensional array from a script and into MySQL. I then, on another page, pull it from the database and unserialize it, and then proceed to print it out with this,
$s = "SELECT * FROM gator_historical_data WHERE channelid = '{$chanid}'";
$r = $link->query($s);
$comboarray = array();
while ($row = mysqli_fetch_assoc($r)) {
$comboarray[] = unserialize($row['dataarray']);
}
foreach ($comboarray as $item) {
$desc = $item['content']['description'];
$title = $item['content']['title'];
$datetime = $item['datetime'];
// ... ^^^ problems getting array data
}
The problem is that it doesn't take the full array from MySQL, only the first entry and thus only prints the first 'array'. So where the returned value from dataarray looks like this (var_dump): http://pastebin.com/raw.php?i=Z0jy55sM the data stored into the unserialized $comboarray only looks like this (var_dump): http://pastebin.com/raw.php?i=Ycwwa924
TL;DR: Pulling a serialized multidimensional array from a database, unserializing and it loses all arrays after the first one.
Any ideas what to do?
The string you've got is a serialized string plus something more at the end that is also a serialized string again and again:
a:3:{s:6:"source";s:25:"World news | The Guardian";s:8:"datetime ...
... story01.htm";}}a:3:{s:6:"source";s:16:"BBC News - World";
^^^
This format is not supported by PHP unserialize, it will only unserialize the first chunk and drop everything at the end.
Instead create one array, serialize it and store that result into the database.
Alternatively you can try to recover for the moment by un-chunking the string, however in case the paste was done right, there are more issues. But on the other hand the paste obvious isn't the done fully correct.

Storing mysqli_query into multidimensional php array and utilizing that array as input to highcharts

I have a question on saving mysqli_fetch_array into multidimensional php array,I have month and amount as data, ex January-12345.0987,February-87654.3456 etc, I am able to get the data from database and able to store it as two different arrays, but I would like to store it in single one and then I want to use that array to send input to highcharts. Can any one please suggest me, below is the code I used for storing the retrieved data into two different arrays
$month=array();
$amount=array();
$i=0;
while($user_data = mysqli_fetch_array($data))
{
//echo 'inside while loop';
$month[$i]=$user_data['month'];
$amount[$i]=$user_data['monthavg'];
$i++;
//$month[$i][$i]=$user_data['month']['monthavg'];
}
I should either use a two dimensional array (the boring way)
$records = mysqli_fetch_all($data);
// Access array of attributes of the first row
var_dump($records[0]);
// Access attribute 'month' of first row
var_dump($records[0]['month']);
// Access attribute 'monthavg' of first row
var_dump($records[0]['monthavg']);
or objects (the cool way):
$records = array();
while($record = mysqli_fetch_object($data))
{
$actualData[] = $record;
}
// Access array of attributes of the first row
var_dump($records[0]);
// Access attribute 'month' of first row
var_dump($records[0]->month);
// Access attribute 'month' of first row
var_dump($records[0]->monthavg);
Then write your JSON or CSV response for your highchart JavaScript app:
$out = fopen('php://output', 'w');
fputcsv($out, $records);
fclose($out);
I recommned you to prepare correct array structure in the php, then use json_encode(). In the javascript use $.getJSON() and load your data. As a result you avoid csv / loading files and parsing it again.

Categories