I have fetched data from MySQL and echoed JSON encoded data as follows:
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$myjsons[$i] = json_encode(array($row));
$i++;
}
echo json_encode($myjsons);
And I have a Javascript function that reads the string and shows it in a text box:
if(ajaxRequest.readyState == 4){
$.post('userfind.php', function(data) {
$("#txtfld").val(data);
var arr =data.slice(1);
var user_arr = arr.slice(0,-1);
var json = user_arr,
obj = JSON.parse(json);
alert(obj.user_id);
$("#resultTXT").val(obj.user_id);
},'json'
);}
}
ajaxRequest.open("POST", "userfind.php", true);
ajaxRequest.send(null);
}
The problem is that txtfld shows the string as [{"user_id":"2790","fre.....tst":""}] and resultTXT shows nothing because of the two [ ]. I have tried to remove them using slice but it seems that the slice doesn't work on JSON strings. What else can I do to remove [ ] so that the resultTXT shows the user_id?
Thanks
you convert the array 2 times to json.
php doesn't need the a index for the next array element
i would also add the correct header "application/json"
$row is already a associative array
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
while ($row = mysql_fetch_assoc($result)) {
$myjsons[] = $row;
}
header('Content-type: application/json');
echo json_encode($myjsons);
this gives you a proper formatted json
to access your json in javascript u do:
var obj=JSON.parse(json);
i assume that your mysql returns a list of orders or users [{"user_id":1},{"user_id":2}] so if you want to access the first user's id:
obj[0].user_id
but if i misunderstand u could post more info about your json.
Related
This question already has answers here:
JSON encode MySQL results
(16 answers)
Closed 1 year ago.
I have a mysqli query which I need to format as JSON for a mobile application.
I have managed to produce an XML document for the query results, however I am looking for something more lightweight. (See below for my current XML code)
$mysql = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME) or die('There was a problem connecting to the database');
$stmt = $mysql->prepare('SELECT DISTINCT title FROM sections ORDER BY title ASC');
$stmt->execute();
$stmt->bind_result($title);
// create xml format
$doc = new DomDocument('1.0');
// create root node
$root = $doc->createElement('xml');
$root = $doc->appendChild($root);
// add node for each row
while($row = $stmt->fetch()) :
$occ = $doc->createElement('data');
$occ = $root->appendChild($occ);
$child = $doc->createElement('section');
$child = $occ->appendChild($child);
$value = $doc->createTextNode($title);
$value = $child->appendChild($value);
endwhile;
$xml_string = $doc->saveXML();
header('Content-Type: application/xml; charset=ISO-8859-1');
// output xml jQuery ready
echo $xml_string;
Simply create an array from the query result and then encode it
$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$myArray = array();
$result = $mysqli->query("SELECT * FROM phase1");
while($row = $result->fetch_assoc()) {
$myArray[] = $row;
}
echo json_encode($myArray);
output like this:
[
{"id":"31","name":"product_name1","price":"98"},
{"id":"30","name":"product_name2","price":"23"}
]
If you want another style, you can change fetch_assoc() to fetch_row() and get output like this:
[
["31","product_name1","98"],
["30","product_name2","23"]
]
Here's how I made my JSON feed:
$mysqli = new mysqli('localhost', 'user', 'password', 'myDatabaseName');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM phase1")) {
$tempArray = array();
while ($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
$result->close();
$mysqli->close();
As mentioned, json_encode will help you. The easiest way is to fetch your results as you already do it and build up an array that can be passed to json_encode.
Example:
$json = array();
while($row = $stmt->fetch()){
$json[]['foo'] = "your content here";
$json[]['bar'] = "more database results";
}
echo json_encode($json);
Your $json will be a regular array with each element in it's own index.
There should be very little changed in your above code, alternativly, you can return both XML and JSON since most of the code is the same.
There is one essential thing about JSON - the data must be UTF-8 encoded. Therefore, the proper encoding must be set for the database connection.
The rest is as silly as any other database operation
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
$db->set_charset('utf8mb4');
$sql = 'SELECT DISTINCT title FROM sections ORDER BY title ASC';
$data = $db->query($sql)->fetch_all(MYSQLI_ASSOC);
echo json_encode($data);
I managed to run this code:
<?php
//create an array
$emparray = array();
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
return json_encode($emparray);
If you have mysqlnd extension installed + enabled in php, you can use:
$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$result = $mysqli->query("SELECT * FROM phase1");
//Copy result into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($resultArray);
mysqli::fetch_all() needs mysqlnd driver to be installed before you
can use it.
I'm doing an SQL SELECT to retrieve client data to then generate an email from.
The $param that is being parsed to the API is an object:
var param = {
delivery_id: "string",
order_id: "string",
}
The order_id is then being used to query a second table:
$param = $_REQUEST['param'];
$param = json_decode($param);
$collname = "orders";
$sql = 'SELECT * FROM '.$collname.' WHERE `id` = '.$param->order_id;
$result = $conn->query($sql);
//$conn is defined externally, and is not the cause of the problem
$aData = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$aData[] = $row;
}
sendEmail($aData);
} else {
echo "Error";
}
mysqli_close($conn);
This first query makes perfect sense, and when the $aData is being returned to the front end as a string, it looks like expected; an array of objects (one object).
But when I try to access it in the sendEmail function, it can't access the key values. Same when I try to echo json_encode($aData[0]->id) (doesn't work) instead of just echoing json_encode($aData[0]) (works).
The email is actually sent to the hard-coded BCC-mail, but without any of the values within the array.
function sendEmail(&$aData){
$to = $aData[0]->contact_email;
$subject = "".$aData[0]->id;
$txt = "Something something ".$aData[0]->contact.",
something something.
";
$headers = "From: email#email.com" . "\r\n" .
"BCC: email#email.com";
mail($to,$subject,$txt,$headers);
}
How do I access the object keys in the API?
EDIT: question answered by S.DEV. Since data was returned as associative array and not an object, correct targeting syntax was $aData[0]['id'].
You can try as following:
while($row = $result->fetch_assoc()) {
//$aData[] = $row;
sendEmail($row);
}
//function sendEmail(&$aData){
function sendEmail($aData){
What I am trying to do doesn't feel difficult, but for some reason I can't seem to find the correct way to ouput this JSON array, from php.
PHP code:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$a = array();
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP DateTime
$a = array(
"time" => $dt->format('Y-m-d H:i:s'),
"signal" => $row['signal'],
"symbol" => $row['symbol'],
"price" => $row['price'],
"timeframe" => $row['timeframe'],
"epoch" => $row['time']);
echo json_encode($a, JSON_UNESCAPED_SLASHES);
}
Output:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
{
"time":"2016-11-14 17:07:59",
"signal":"Sell",
"symbol":"GBPJPYecn",
"price":"135.13200",
"timeframe":"M1",
"epoch":"1479143279"
}
The correct output should have },{ NOT }{ between each object.
What I am ultimately trying to do:
function getTrades(a) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "core/engine.php",
data: "q=data&account="+a,
dataType: "html", //expect html to be returned
success: function(response){
if(response=="nologin") {
alert("Sorry, but either your account is not activated or your login is incorrect!");
} else {
var j = $.parseJSON(response);
$.each(j, function (k, v) {
$("#trades").html('<span class="tradesignal"><!-- span class="signalarrowup"></span-->'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span> <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button> '+v.price+' '+v.timeframe+'</span>');
});
}
//alert(response);
console.log(response);
}
});
}
Each {json},{json} object will have its data printed into a span on an html page.
Appreciate the guidance!
Try creating a results array and push each one of the objects there, then after the loop finishes, convert the array to json and print it.
example:
$results = array();
$i = 0;
while($row = mysqli_fetch_array($result)){
//your code here
$a = array("time" => ....);
$results[] = $a; //this will add $a to $results
}
echo json_encode($results, JSON_UNESCAPED_SLASHES);
Just to add a little more explanation in addition to the code the other answers are suggesting. The problem is, you aren't outputting a JSON array. Each time you do
echo json_encode($a, JSON_UNESCAPED_SLASHES);
inside your loop, you output a valid JSON object like:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
However, when you output the subsequent objects, getting a result like
{
"time": ...
}
{
"time": ...
}
You no longer have valid JSON. Even though each of the individual objects is valid, concatenating them together isn't. Simply adding a comma between the objects will still not make it valid. In order to produce an actual JSON array, the comma separated objects will need to be enclosed in square brackets like this:
[
{
"time": ...
},
{
"time": ...
}
]
That's why you need to add each of the arrays you're creating in the loop to an outer array and then json_encode the whole thing after the loop. The outer PHP array will become the outer JSON array you need.
As Xorifelse said, you want to put the data in an array, and then call json_encode on the array. Here is a code that should work:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP Date
$a[] = array("time" => $dt->format('Y-m-d H:i:s'), "signal" => $row['signal'], "symbol" => $row['symbol'], "price" => $row['price'], "timeframe" => $row['timeframe'],"epoch" => $row['time']);
}
echo json_encode($a, JSON_UNESCAPED_SLASHES);
This question already has answers here:
JSON encode MySQL results
(16 answers)
Closed 1 year ago.
I've spent a couple of hours looking through several the similar answers before posting my problem.
I'm retrieving data from a table in my database, and I want to encode it into a JSON. However, the output of json_encode() is only valid when the table has one single row. If there is more than one row, the test at http://jsonlint.com/ returns an error.
This is my query:
$result = mysql_query($query);
$rows = array();
//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
$rows['data'] = $r;
//echo result as json
echo json_encode($rows);
}
That gets me the following JSON:
{
"data":
{
"entry_id":"2",
"entry_type":"Information Relevant to the Subject",
"entry":"This is my second entry."
}
}
{
"data":{
"entry_id":"1",
"entry_type":"My Opinion About What Happened",
"entry":"This is my first entry."
}
}
When I run the test at http://jsonlint.com/, it returns this error:
Parse error on line 29:
..."No comment" }}{ "data": {
---------------------^
Expecting 'EOF', '}', ',', ']'
However, if I only use this first half of the JSON...
{
"data":
{
"entry_id":"2",
"entry_type":"Information Relevant to the Subject",
"entry":"This is my second entry."
}
}
... or if I only test the second half...
{
"data":{
"entry_id":"1",
"entry_type":"My Opinion About What Happened",
"entry":"This is my first entry."
}
}
... the same test will return "Valid JSON".
What I want is to be able to output in one single [valid] JSON every row in the table.
Any suggestion will be very much appreciated.
The problem is you're spitting out separate JSON for each row, as opposed to doing it all at once.
$result = mysql_query($query);
$rows = array();
//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
// $rows[] = $r; has the same effect, without the superfluous data attribute
$rows[] = array('data' => $r);
}
// now all the rows have been fetched, it can be encoded
echo json_encode($rows);
The minor change I've made is to store each row of the database as a new value in the $rows array. This means that when it's done, your $rows array contains all of the rows from your query, and thus you can get the correct result once it's finished.
The problem with your solution is that you're echoing valid JSON for one row of the database, but json_encode() doesn't know about all the other rows, so you're getting a succession of individual JSON objects, as opposed to a single one containing an array.
You need to change your PHP code into something like this:
$result = mysql_query($query);
$rows = array();
//retrieve every record and put it into an array that we can later turn into JSON
while($r = mysql_fetch_assoc($result)){
$rows[]['data'] = $r;
}
//echo result as json
echo json_encode($rows);
I think you should do
$rows = array();
while($r = mysql_fetch_assoc($result)){
$rows[]['data'] = $r;
}
echo json_encode($rows);
echo should be placed outside of the loop.
I was trying the same in my PHP, so I came whit this...
$find = mysql_query("SELECT Id,nombre, appaterno, apmaterno, semestre, seccion, carrera FROM Alumno");
//check that records exist
if(mysql_num_rows($find)>0) {
$response= array();
$response["success"] = 1;
while($line = mysql_fetch_assoc($find)){}
$response[] = $line; //This worked for me
}
echo json_encode($response);
} else {
//Return error
$response["success"] = 0;
$response["error"] = 1;
$response["error_msg"] = "Alumno could not be found";
echo json_encode($response);
}
And, in my Android Class...
if (Integer.parseInt(json.getString("success")) == 1) {
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
if (!value.equals(1)) {
JSONObject jsonArray = (JSONObject) value;
int id = jsonArray.getInt("Id");
if (!db.ExisteAlumo(id)) {
Log.e("DB EXISTE:","INN");
Alumno a = new Alumno();
int carrera=0;
a.setId_alumno(id);
a.setNombre(jsonArray.getString("nombre"));
a.setAp_paterno(jsonArray.getString("appaterno"));
a.setAp_materno(jsonArray.getString("apmaterno"));
a.setSemestre(Integer.valueOf(jsonArray.getString("semestre")));
a.setSeccion(jsonArray.getString("seccion"));
if(jsonArray.getString("carrera").equals("C"))
carrera=1;
if(jsonArray.getString("carrera").equals("E"))
carrera=2;
if(jsonArray.getString("carrera").equals("M"))
carrera=3;
if(jsonArray.getString("carrera").equals("S"))
carrera=4;
a.setCarrera(carrera);
db.addAlumno(a);
}
}
} catch (JSONException e) {
// Something went wrong!
}
}
I must have spent 15 hours on this issue. Every variation discussed above was tried. Finally I was able to get the 'standard solution' working. The issue, very oddly, appears to be this:
When the interval is set beyond 14 hours, json appears to be unable to parse it. There must be a limit to JSON.
$sql= "SELECT cpu_name, used, timestamp FROM tbl_cpu_use WHERE timestamp>(NOW() - INTERVAL 14 HOUR) ORDER BY id";
$result=mysql_query($sql);
if ($result){
$i=0;
$return =[];
while($row = mysql_fetch_array($result, MYSQL_NUM)){
$rows[] = $row;
}
echo json_encode($rows);
}else{
echo "ERROR";
}
I've looked through various other questions on SO, but can't quite get the right answer. Basically, I have an array that needs data from a MySql database. Here's what I've tried:
var $name = "Foo",
$x = 10,
$bar =
<? php
$barQuery = mysql_query("SELECT item FROM table WHERE name = '$name' AND number = '$x'");
$barArray = array();
while ($r = mysql_fetch_assoc($barQuery))
{
$barArray[] = $r['item'];
}
echo json_encode($barArray);
?>;
EDIT: I then post this to a .php file, and print the returned data:
$.post("file.php", {bar: JSON.stringify($bar), name: $name}).done(function(data)
{
$('body').html(data);
window.print();
setTimeout("location.reload(true)", 500);
});
However, I get an error saying "syntax error, unexpected T_VARIABLE". Is it not possible to populate a JS array this way, or is there another way to do it?
var $name = "Foo",
$x = 10,
$bar = "
<?php
$barQuery = mysql_query("SELECT item FROM table WHERE name = '$name' AND number = '$x'");
$barArray = array();
while ($r = mysql_fetch_assoc($barQuery))
{
$barArray[] = $r['item'];
}
echo json_encode($barArray);
?>";
You have a superfluous space inside the PHP opening tag:
<? php
^--- this shouldn't be there
As it stands, the <? is parsed as a short open tag, and so the php is parsed as a(n undefined) constant, which is immediately followed by $barQuery—hence the syntax error that you see: unexpected T_VARIABLE.