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"}]
Related
I've got a database structure like this.
I'm willing to get row as a json object for Json.net.
My php code is this
$check_query = mysqli_query($conn, "select * from users where name = '$name' and password = '$pass'");
$rows = array();
while($r = mysqli_fetch_assoc($get_query)) {
$rows[] = $r;
}
if(count($rows) > 0) {
echo json_encode($rows[0]);
}
I'm getting json as this.
{"unique_id":"pcg9sy26","name":"w","password":"w","mail":"alpsavrum#gmail.com","age":18,"locale":"Turkey","city":"Istanbul","subscriptions":"[\"electronics\", \"vacations\"]","history":null,"token":"12562f39b990da0433d7be71992ed634"}
As you can see, subscriptions value is string. I need it to be array as it seems.
{"unique_id":"pcg9sy26","name":"w","password":"w","mail":"alpsavrum#gmail.com","age":18,"locale":"Turkey","city":"Istanbul","subscriptions":[\"electronics\", \"vacations\"],"history":null,"token":"12562f39b990da0433d7be71992ed634"}
Is there any way to achieve this. ?
Thanks a lot !
The way you're retrieving that data is giving you the JSON value as a string. Storing it as JSON in the database is a good idea if it's actually JSON data, but the mysqli driver will not automatically de-serialize it for you. If you want that sort of behaviour you'll need to use an ORM.
When you're having trouble with double encoding, check with var_dump to see what you're actually working with. That would reveal the subscriptions key contains a JSON string, not an array as expected.
What you'll have to do is manually de-serialize it prior to JSON encoding:
if (isset($r['subscriptions'])) {
$r['subscriptions'] = json_decode($r['subscriptions']);
}
$rows[] = $r;
You will need to do this for any and all JSON encoded fields your results might have.
This way you're JSON encoding a proper PHP data structure and not one that's part PHP and part JSON string.
Try json decode function in whatever language you are reading it.
Decode the JSON response and then print it
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);
I using codeigniter. I want to retrive data from database and convert it into JSON object not JSON array.I'm using following code
public function json()
{
$content = $this->db->get('todolist'); //todolist table name
$data = $content->result_array();
echo json_encode($data);
}
Above code is converting database into JSON array.
Output
[{"todo_id":"1","todo_content":"Homework","date":"2016-05-05","iscomplete":null,"imagelink":"Lighthouse.jpg"},{"todo_id":"2","todo_content":"exam","date":"2015-04-21","iscomplete":null,"imagelink":"Desert.jpg"},{"todo_id":"3","todo_content":"Lab report","date":"2014-08-29","iscomplete":null,"imagelink":"FB_IMG_14700753538617403.jpg"}]
What will be best way to convert it into JSON object
Sangam try to understand the concept, check the following line:
$data = $content->result_array(); // $data is an array
echo json_encode($data); // here you are converting it into an json object
Your $data array contains more than one index in it that's why the json object is having multiple {} inside [];
You want to json_encode($data, JSON_FORCE_OBJECT).
The JSON_FORCE_OBJECT flag, as the name implies, forces the json output to be an object, even when it otherwise would normally be represented as an array.
Refer: PHP Array to Json Object
You can use JSON_FORCE_OBJECT see the example below.
echo json_encode($data, JSON_FORCE_OBJECT);
Assuming you're only getting one row back from your query.
change
echo json_encode($data);
to
echo json_encode($data[0]);
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.
I've this php code that passes results to a jquery getJSON function that doesn't work properly.
here is my code:
$data["total"]=mysql_num_rows($s);
while ($r = mysql_fetch_array($s))
{
$ris_sql["utente"]=tv($r["utente"]);
$ris_sql["contratto"]=tv($r["contratto"]);
$ris_sql["login"]=tv($r["login"]);
$ris_sql["piattaforma"]=tv($r["piattaforma"]);
$ris_sql["azione"]=tv(format_valid($r["azione"]));
$ris_sql["data"]=tv($r["data"]);
$ris_sql["note"]=tv(str_replace("<br>","",$r["note"]));
$riga[]=$ris_sql;
}
$data["rows"]=json_encode($riga, JSON_FORCE_OBJECT);
echo json_encode($data);
If I try to use firebug I see that my rows elements in JSON result like a string instead a series of objects, what is wrong in my code??
You are double-encoding the $riga JSON. Don't separately encode the $riga part prior to encoding the rest of the $data array you're sending back to the browser.
// Instead of
$data["rows"] = json_encode($riga, JSON_FORCE_OBJECT);
// This double-encodes the contents of $data before outputting back to the browser or ajax call
echo json_encode($data);
// Just do:
echo json_encode($data, JSON_FORCE_OBJECT);
If the format isn't what you expect, instead you can cast $riga from an array to an object and then encode the whole thing without JSON_FORCE_OBJECT.
// Cast $riga from an assoc array to an instance of stdClass
$data['rows'] = (object)$riga;
// And then JSON encode the whole $data
echo json_encode($data);