What is the easiest way to retrieve data from the database, and convert the data to a JSON String?
Is there any kind of helper class? or am I supposed to loop through the columns in my dataset to create the JSON string?
You can use the json_encode function to convert a native PHP array or stdClass object to it's corresponding JSON representation:
$result = $db->query('SOME QUERY');
$set = array();
if($result->num_rows) {
while($row = $result->fetch_array()) {
$set[] = $row;
}
}
echo json_encode($set);
Make an array from mySQL, and json_encode() it
Yes, use PHP's functions to handle JSON encoding.
Here's an example I got from this SO question:
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
Have you seen the json_encode() function? It takes an array as input and outputs JSON. So the most basic would be a two-dimensional array representing your table as input to json_encode
If you use the json_encode function then you're depending on somebody else's interpretation of the right way to format the json. Which means that you might come out with weird json, or have to contort your classes in evil ways to make the json come out right.
Just something to think about.
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
I am storing html in a mysql database as raw html. I am pulling the contents and placing it into an array as follows. The array is the json_encoded, but if there is any double quotes or urls then the javascript displaying the JSON string breaks.
Is it possible to encode html to work through JSON?
Here is an extract of what I am using
<?php
$rows = array();
$sql ="SELECT html FROM table";
try {
$sth = $dbh->query($sql);
while($r = $sth->fetch(PDO::FETCH_OBJ)) {
$rows[] = $r;
}
}
catch(PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that. $e";
}
?>
var json = JSON.parse('<?php print json_encode(json_encode($rows)); ?>');
The json string currently outputting throws a javascript error saying unexpected <
[{"html":"<a href="http:\/\/www.url.com">\n<img src="http:\/\/www.url.com\/img\/logo.png">\n<\/a>"}]
Please no lectures on why this may be a bad thing. This is what my client has requested specifically and I just need to know if it is possible.
I agree with Mark B's answer but you could use fetchAll() and json_encode() the result of this function. Why do you use PDO Object fetching instead of array fetching?
<?php
$rows = array();
$sql ="SELECT hmtl FROM table";
try {
$sth = $dbh->query($sql);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that. $e";
}
?>
var json = <?= json_encode($rows); ?>;
Moreover consider getting it via AJAX.
There's no need for the json.parse business. JSON IS valid javascript after all, so a simple
var json = <?php echo json_encode($rows); ?>;
is all you need.
The line
var json = JSON.parse('<?php print json_encode(json_encode($rows)); ?>');
...is susceptible to single quotes in the resulting JSON (and other things; you'd have to double-escape lots of stuff). But you don't need or want to do that. Do this:
var json = <?php print json_encode(json_encode($rows)); ?>;
json_encode returns valid JSON, and JSON is a subset of JavaScript object initializer syntax, and so the above will result in valid JavaScript code describing the object. If you're outputting JavaScript code, as you appear to be from that line, there's no reason to go indirectly through a string. And as you've found, there's a reason not to.
Before filling the JSON object, you could use htmlentities() to convert all applicable characters to HTML entities, and then when printing them out just use html_entity_decode() if you use an ISO standard as character set. Sorry if I might have misunderstood the question.
I'm trying to pass an array to Javascript after it has sent a GET request to PHP.
Sending and retrieving the data works perfectly but I couldn't find anything about passing the data back as an array like this:
<?php
$result = mysql_query('blablabla');
//converting $result to an array?
echo $result_as_javascript_array;
?>
<script>
$('result').innerHTML = httpGet.responseText
</script>
Convert the data you get from MySQL to JSON. First build a "normal" PHP array as you would normally do, then pass it through the json_encode() function and return it.
On the client you have to parse the JSON string into a JS array or object. See this SO question for details: Parse JSON in JavaScript?
And please use something else for accessing MySQL. The extension you are using is basically obsolete: http://si1.php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated
you should use json_encode, which works fine, when directly assigning output to a javascript variable
<?php
$result = mysql_query('blablabla');
//first convert result to an associative array
$myarray = array();
while($fetch = mysql_fetch_assoc($result)){
$myarray[]=$fetch;
}
//converting $result to an array?
echo "<script>";
echo "var myArray = ".json_encode($myarray).";";
echo "</script>";
?>
<script>
//now you can use myArray global javascript variable
$('result').innerHTML = myArray.join(",");
</script>
You are looking for json_encode.
Use json_encode like this:
<?php
$result = mysql_query('blablabla');
//converting $result to an array?
echo json_encode($result);
?>
You probably won't want to put the response text right into the innerHTML of your element though unless you are wanting to display the json text in the element.
$arr = array();
while ($row = mysql_fetch_array($result)) {
$arr[] = $row;
}
echo $arr;
However, mysql_ is deprecated, use mysqli instead.
If you want to pass it as JSON, use this:
echo json_encode($arr);
I am having a problem with the last comma when I am using PHP echoing JSON Array to android
Here is my code
If ($commentResult>0)
echo "[";
{
while ($row = mysql_fetch_array($commentResult)) {
echo json_encode($row).",";
}
echo "]";
Android can't read this, it printed out JSONException:Vale at 3 is null
Why are you trying to re-invent the wheel? If you want to give an entire array then put json_encode over the entire array instead of trying to manually build it.
$comments=array();
if($commentResult>0){
while($row=mysql_fetch_array($commentResult)){
$comments[]=$row;
}
}
echo json_encode($comments);
*Also, a side tip, don't use mysql_ functions. Instead use PDO or mysqli, which are better supported and get you rid of this whole while($row) business.*
The way you form you json is really strange. Don't know if it's an issue but you can try it in a more clean way:
if ($commentResult) {
for ($data = array(); $row = mysql_fetch_array($commentResult); $data[] = $row);
echo json_encode($data);
}
What ever JSON you are generating using PHP, Just verify that in http://jsonlint.com/. if output is wrong it wont validate other wise its OK from PHP side.
I have a jQuery post that returns some objects.
So, I have a DB query result that I do json_encode($result) and then I send it as a response in the success function inside the jQuery post.
If I console.log the response I see multiple objects. What I want is to send the response as an array of arrays.
In PHP
json_encode($results)
In javascript:
success: function(json) {
console.log(json);
}
In console log:
[>Object , >Object , >Object]
Any ideas?
Your $results in php is an array of objects or of associative arrays. Make it an array of numerically-indexed arrays before you send with casting:
// ASSUMING each $result object does not have its own nested arrays
foreach ($results as &$result) {
$result = array_values((array) $result);
}
Note you will lose the ability to get items by column name.
But please step back and think about where your $result comes from.
If you are using mysql driver, consider doing this when building your result:
$results = array();
// Note we use MYSQL_NUM option, so $row looks like array('col1value', 'col2value')
while (FALSE !== ($row = mysql_result_array($resource, MYSQL_NUM))) {
$results[] = $row;
}
json_encode($results);
In Javascript with JQuery:
jQuery.makeArray();
http://api.jquery.com/jQuery.makeArray/
In php, casting:
$aArray = (array) $oObject;
json encode will encode a string as a json OBJECT which in javascript is an object. in javascript an array is simply an object with special helper functions. there shouldn't be a need to create an array from the object as you can manipulate an object as easily as you can manipulate an array.