Pushing data to a JSON generated with json_encode - php

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);

Related

Need to print mysql data in to json in a format

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

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.

Object of class stdClass could not be converted to string - laravel

I am following this documentation
to implement export to Excel in my laravel 4 project.
So am trying to generate excel file from array like this:
//$results is taken with db query
$data = array();
foreach ($results as $result) {
$result->filed1 = 'some modification';
$result->filed2 = 'some modification2';
$data[] = $result;
}
Excel::create('Filename', function($excel) use($data) {
$excel->sheet('Sheetname', function($sheet) use($data) {
$sheet->fromArray($data);
});
})->export('xls');
But this raises exception:
Object of class stdClass could not be converted to string
What am I doing wrong ?
UPDATE:
Tried this:
$data = get_object_vars($data);
which results in:
get_object_vars() expects parameter 1 to be object, array given
This:
$data = (array)$data;
Results in the initial error.
Try this simple in one line of code:-
$data= json_decode( json_encode($data), true);
Hope it helps :)
$data is indeed an array, but it's made up of objects.
Convert its content to array before creating it:
$data = array();
foreach ($results as $result) {
$result->filed1 = 'some modification';
$result->filed2 = 'some modification2';
$data[] = (array)$result;
#or first convert it and then change its properties using
#an array syntax, it's up to you
}
Excel::create(....
You might need to change your object to an array first. I dont know what export does, but I assume its expecting an array.
You can either use
get_object_vars()
Or if its a simple object, you can just typecast it.
$arr = (array) $Object;
If you have a Collection of stdClass objects, you could try with this:
$data = $data->map(function ($item){
return get_object_vars($item);
});
I was recieving the same error when I was tring to call an object element by using another objects return value like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->$this->array1->country;// Error line
The above code was throwing the error and I tried many ways to fix it like; calling this part $this->array1->country in another function as return value, (string), taking it into quotations etc. I couldn't even find the solution on the web then i realised that the solution was very simple. All you have to do it wrap it with curly brackets and that allows you to target an object with another object's element value. like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->{$this->array1->country};
If anyone facing the same and couldn't find the answer, I hope this can help because i spend a night for this simple solution =)
This is easy all you need to do is something like this Grab your contents like this
$result->get(filed1) = 'some modification';
$result->get(filed2) = 'some modification2';

json encoding 2 dimension array

I have the following in php:
$query = mysql_query($sql);
$rows = mysql_num_rows($query);
$data['course_num']=$rows;
$data['course_data'] = array();
while ($fetch = mysql_fetch_assoc($query) )
{
$courseData = array(
'course_name'=>$fetch['course_name'],
'training_field'=>$fetch['training_field'],
'speciality_field'=>$fetch['speciality_field'],
'language'=>$fetch['language'],
'description'=>$fetch['description'],
'type'=>$fetch['type'],
);
array_push($data['course_data'],$courseData);
}
echo json_encode($data);
when I receive the result of this script in jquery (using post)
I log it using :
console.log(data['course_data']);
and the output is :
[Object { course_name="Introduction to C++", training_field="Engineering" , speciality_field="Software", more...}]
But I can't seem to figure out how to access the elements.
I tried
data['course_data'].course_name
data['course_data']['course_name']
Nothing worked. Any ideas
When you array_push($data['course_data'],$courseData); you are actually putting $courseData at $data['course_data'][0] and therefore you would access it in JavaScript as data['course_data'][0]['course_name'].
If you only intend to have one result, instead of array_push($data['course_data'],$courseData); you should just specify $data['course_data'] = $courseData. Otherwise, you should iterate over data['course_data'] like so:
for (i in data['course_data']) {
console.log(data['course_data'][i]['course_name']);
}
You should specify the index in the first array for instance
data['course_data'][0]['course_name'];
you could make it better if you had defined the first array just as variable not a variable within an array
$data['course_data'][0]['course_name']
should do the trick. If not please send the output of var_dump($data)
Assuming the PHP code is correct, you will receive a JSON data like:
{
"course_num":34,
"course_data":[
{
"course_name":"name_value",
....
},
....etc (other object based on SQL result)
]
}
So, if you want to access to the total number of result:
data.course_num
If you want to access to the first element of the list of result:
data.course_data[0]
If you want to access to the name of the first element of the list of result:
data.course_data[0].course_name
or
data.course_data[0]['course_name']
use jquery's parseJSON method to get all the goodies out of the json object...
http://api.jquery.com/jQuery.parseJSON/

Encoding a SELECT statement as JSON, iOS issues

I am trying to JSON encode the results of my SQL SELECT statement using PHP and am unsure if I am formatting my array correctly before encoding.
My PHP code is:
$stmt = $this->db->prepare('SELECT CLINIC.clinic_name AS "clinicname" FROM CLINIC ORDER BY CLINIC.clinic_name ASC');
$stmt->execute();
$stmt->bind_result($clinicname);
$test = array();
while($stmt->fetch()){
$tempArray = array('clinicname' => $clinicname);
array_push($test, $tempArray);
}
$stmt->close();
// Return clinics, encoded with JSON
header('Content-type: application/json');
$json = json_encode($test);
echo $json;
The result of this array creation and encoding is:
[{"clinicname":"Bangor"},{"clinicname":"Belfast"},{"clinicname":"Crumlin"},{"clinicname":"Londonderry"}]
So I have an array of arrays.
Will this be okay for sending as JSON? All the examples I see seem to be a single array. Am I correct so far?
And then, regarding iOS, will the received object be a NSDictionary or an NSArray?
Any help or feedback on the above would be greatly received.
Matt.
Yes, your JSON is properly formatted. Next time you can use a JSON validator to check.
Also, some details on json_encoding.
A [] represents an array and {} represents an object.
In iOS, if this is the result from an http request, it will be of type NSString, and then need to be parsed by something like:
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
which then converts it to NSArray, NSDictionary NSString, etc.
Yes, you can send an array of arrays, and you can acces like the follow way:
$response = json_decode($response,true);
foreach ($response as $resp)
{
echo "<br>";
print_r($resp);
}
json example:
[{"id":"38","first_name":"prueba","second_name":"example","first_surname":"prueba","second_surname":"GONZALEZ","email":"x#x.net","network_login":"x.x","pos_name":"x x","position":"1","active":"1"},{"vhur":"292","first_name":"c","second_name":"example","first_surname":"example","second_surname":null,"email":"example#example.com","network_login":"example.example","pos_name":"example example","position":"2","active":"1"}]

Categories