SyntaxError: JSON.parse: unexpected character when parsing output from PHP - javascript

My php returns something as such:
if(!$result = $db->query($sql)){
echo $db->error;
die('There was an error running the query [' . $db->error . ']');
}
echo 'Total results: ' . $result->num_rows . "\n";
while($row = $result->fetch_assoc()){
echo json_encode($row);
echo "\n";
}
In my javascript, I want to put the output on the page if it's a json object or just log it to the console if it's something else:
var divOutput = function(output) {
try {
// var x = output.trim();
// x = JSON.parse(JSON.stringify(x));
var x = JSON.parse(output);
console.log(x);
$("#dbOut").html(JSON.stringify(x, null, '\t'));
} catch (e) {
console.log(output);
console.log(e);
}
}
var getPlayerByID = function() {
var myNumber = document.getElementById("PlayerInput").value;
$.ajax({
url : "db_funcs.php",
data : {
action : 'getPlayerByID',
a : myNumber,
},
type : 'post',
success : function(output) {
divOutput(output);
}
However it's throwing the JSON parse error when I query the database. How can I do this?
})
}

JSON must be output as a SINGLE monolithic json string. You're building multiple SEPARATE json strings, which is illegal syntax.
Consider JSON to be pretty much equivalent to the right-hand side of a javascript variable assignment:
var foo = this_part_is_json;
e.g. you need to have
var foo = [[stuff from row 1], [stuff from row2], etc...];
but are producing
var foo = [stuff from row1][stuff from row2];
^---syntax error would occur here
You need
$arr = array();
while($row = fetch from db) {
$arr[] = $row;
}
echo json_encode($arr);

It throws the error because you are not only echoing json.
In the line
echo 'Total results: ' . $result->num_rows . "\n"
You already echo something which is not json encoded.
With this code it should work:
//echo 'Total results: ' . $result->num_rows . "\n"; <---- this is not json
$arr = [];
while($row = $result->fetch_assoc()){
$arr[] = $row; //save each row in array
//echo "\n";
}
echo json_encode($arr); //encode all data as json
If you want the number of rows also in the json output add it in the $arr with a key like
$arr["num_rows"] = $result->num_rows;

This is wrong
while($row = $result->fetch_assoc()){
echo json_encode($row);
echo "\n";
}
Try like this
$arr = array();
while($row = $result->fetch_assoc()){
$arr[] = ($row);
}
echo json_encode($arr);
Use json_encode() only once, use arrays to store values in while()

Related

How can I add more than 3 rows to my json output? [duplicate]

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.

Send php object through ajax call [duplicate]

How do I use the json_encode() function with MySQL query results? Do I need to iterate through the rows or can I just apply it to the entire results object?
$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
The function json_encode needs PHP >= 5.2 and the php-json package - as mentioned here
NOTE: mysql is deprecated as of PHP 5.5.0, use mysqli extension instead http://php.net/manual/en/migration55.deprecated.php.
Try this, this will create your object properly
$result = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['object_name'][] = $r;
}
print json_encode($rows);
http://www.php.net/mysql_query says "mysql_query() returns a resource".
http://www.php.net/json_encode says it can encode any value "except a resource".
You need to iterate through and collect the database results in an array, then json_encode the array.
When using PDO
Use fetchAll() to fetch all rows as an associative array.
$stmt = $pdo->query('SELECT * FROM article');
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
When your SQL has parameters:
$stmt = $pdo->prepare('SELECT * FROM article WHERE id=?');
$stmt->execute([1]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
When you need to rekey the table you can use foreach loop and build the array manually.
$stmt = $pdo->prepare('SELECT * FROM article WHERE id=?');
$stmt->execute([1]);
$rows = [];
foreach ($stmt as $row) {
$rows[] = [
'newID' => $row['id'],
'Description' => $row['text'],
];
}
echo json_encode($rows);
When using mysqli
Use fetch_all() to fetch all rows as an associative array.
$res = $mysqli->query('SELECT * FROM article');
$rows = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows);
When your SQL has parameters you need to perform prepare/bind/execute/get_result.
$id = 1;
$stmt = $mysqli->prepare('SELECT * FROM article WHERE id=?');
$stmt->bind_param('s', $id); // binding by reference. Only use variables, not literals
$stmt->execute();
$res = $stmt->get_result(); // returns mysqli_result same as mysqli::query()
$rows = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows);
When you need to rekey the table you can use foreach loop and build the array manually.
$stmt = $mysqli->prepare('SELECT * FROM article WHERE id=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$res = $stmt->get_result();
$rows = [];
foreach ($res as $row) {
$rows[] = [
'newID' => $row['id'],
'Description' => $row['text'],
];
}
echo json_encode($rows);
When using mysql_* API
Please, upgrade as soon as possible to a supported PHP version! Please take it seriously. If you need a solution using the old API, this is how it could be done:
$res = mysql_query("SELECT * FROM article");
$rows = [];
while ($row = mysql_fetch_assoc($res)) {
$rows[] = $row;
}
echo json_encode($rows);
if ($result->num_rows > 0) {
# code...
$arr = [];
$inc = 0;
while ($row = $result->fetch_assoc()) {
# code...
$jsonArrayObject = (array('lat' => $row["lat"], 'lon' => $row["lon"], 'addr' => $row["address"]));
$arr[$inc] = $jsonArrayObject;
$inc++;
}
$json_array = json_encode($arr);
echo $json_array;
} else {
echo "0 results";
}
The code below works fine here!
<?php
$con=mysqli_connect("localhost",$username,$password,databaseName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "the query here";
$result = mysqli_query($con,$query);
$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($con);
?>
The above will not work, in my experience, before you name the root-element
in the array to something, I have not been able to access anything in the
final json before that.
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows['root_name'] = $r;
}
print json_encode($rows);
That should do the trick!
<?php
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DB', 'dishant');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = mysqli_connect(HOST, USER, PASS, DB);
$sql = "select * from demo ";
$sth = mysqli_query($con, $sql);
$rows = array();
while ($r = mysqli_fetch_array($sth, MYSQLI_ASSOC)) {
$row_array['id'] = $r;
array_push($rows, $row_array);
}
echo json_encode($rows);
array_push($rows,$row_array); helps to build an array otherwise it gives the last value in the while loop.
This works like append method of StringBuilder in Java.
My simple fix to stop it putting speech marks around numeric values...
while($r = mysql_fetch_assoc($rs)){
while($elm=each($r))
{
if(is_numeric($r[$elm["key"]])){
$r[$elm["key"]]=intval($r[$elm["key"]]);
}
}
$rows[] = $r;
}
Sorry, this is extremely long after the question, but:
$sql = 'SELECT CONCAT("[", GROUP_CONCAT(CONCAT("{username:'",username,"'"), CONCAT(",email:'",email),"'}")), "]")
AS json
FROM users;'
$msl = mysql_query($sql)
print($msl["json"]);
Just basically:
"SELECT" Select the rows
"CONCAT" Returns the string that results from concatenating (joining) all the arguments
"GROUP_CONCAT" Returns a string with concatenated non-NULL value from a group
One more option using FOR loop:
$sth = mysql_query("SELECT ...");
for($rows = array(); $row = mysql_fetch_assoc($sth); $rows[] = $row);
print json_encode($rows);
The only disadvantage is that loop for is slower then e.g. while or especially foreach
For example
$result = mysql_query("SELECT * FROM userprofiles where NAME='TESTUSER' ");
1.) if $result is only one row.
$response = mysql_fetch_array($result);
echo json_encode($response);
2.) if $result is more than one row. You need to iterate the rows and save it to an array and return a json with array in it.
$rows = array();
if (mysql_num_rows($result) > 0) {
while($r = mysql_fetch_assoc($result)) {
$id = $r["USERID"]; //a column name (ex.ID) used to get a value of the single row at at time
$rows[$id] = $r; //save the fetched row and add it to the array.
}
}
echo json_encode($rows);
I solved like this
$stmt->bind_result($cde,$v_off,$em_nm,$q_id,$v_m);
$list=array();
$i=0;
while ($cresult=$stmt->fetch()){
$list[$i][0]=$cde;
$list[$i][1]=$v_off;
$list[$i][2]=$em_nm;
$list[$i][3]=$q_id;
$list[$i][4]=$v_m;
$i=$i+1;
}
echo json_encode($list);
This will be returned to ajax as result set
and by using json parse in javascript part like this :
obj = JSON.parse(dataX);
we could simplify Paolo Bergantino answer like this
$sth = mysql_query("SELECT ...");
print json_encode(mysql_fetch_assoc($sth));
We shouldn't see any use of mysql_ functions in modern applications, so either use mysqli_ or pdo functions.
Explicitly calling header("Content-type:application/json"); before outputting your data payload is considered to be best practice by some devs. This is usually not a requirement, but clarifies the format of the payload to whatever might be receiving it.
Assuming this is the only data being printed, it is safe to print the json string using exit() which will terminate the execution of the script as well. This, again, is not essential because echo will work just as well, but some devs consider it a good practice to explicitly terminate the script.
MySQLi single-row result set from query result set object:
exit(json_encode($result->fetch_assoc())); // 1-dimensional / flat
MySQLi multi-row result set from query result set object:
Prior to PHP 8.1.0, available only with mysqlnd.
exit(json_encode($result->fetch_all(MYSQLI_ASSOC))); // 2-dimensional / array of rows
MySQLi single-row result set from prepared statement:
$result = $stmt->get_result();
exit(json_encode($result->fetch_assoc())); // 1-dimensional / flat
MySQLi multi-row result set from prepared statement:
$result = $stmt->get_result();
exit(json_encode($result->fetch_all(MYSQLI_ASSOC))); // 2-dimensional / array of rows
PDO single-row result set from query result set object:
exit(json_encode($result->fetch(PDO::FETCH_ASSOC))); // 1-dimensional / flat
PDO multi-row result set from query result set object:
exit(json_encode($result->fetchAll(PDO::FETCH_ASSOC))); // 2-dimensional / array of rows
PDO single-row result set from prepared statement:
exit(json_encode($stmt->fetch(PDO::FETCH_ASSOC))); // 1-dimensional / flat
PDO multi-row result set from prepared statement:
exit(json_encode($stmt->fetchAll(PDO::FETCH_ASSOC))); // 2-dimensional / array of rows
Obey these rules to prevent the possibility of generating invalid json.:
you should only call json_encode() after you are completely finished manipulating your result array and
you should always use json_encode() to encode the payload (avoid the urge to manually craft a json string using other string functions or concatenation).
If you need to iterate your result set data to run php functions or provide functionality that your database language doesn't offer, then you can immediately iterate the result set object with foreach() and access values using array syntax -- e.g.
$response = [];
foreach ($result as $row) {
$row['col1'] = someFunction($row['id']);
$response[] = $row;
}
exit(json_encode($response));
If you are calling json_encode() on your data payload, then it won't make any difference to whether the payload is an array of arrays or an array of objects. The json string that is created will have identical syntax.
You do not need to explicitly close the database connection after you are finished with the connection. When your script terminates, the connection will be closed for you automatically.
Considering there's not really any NESTED json objects in mysql in general etc., it's fairly easy to make your own encoding function
First, the function to retrieve the mysqli results in an array:
function noom($rz) {
$ar = array();
if(mysqli_num_rows($rz) > 0) {
while($k = mysqli_fetch_assoc($rz)) {
foreach($k as $ki=>$v) {
$ar[$ki] = $v;
}
}
}
return $ar;
}
Now, function to encode array as json:
function json($ar) {
$str = "";
$str .= "{";
$id = 0;
foreach($ar as $a=>$b) {
$id++;
$str .= "\"".$a."\":";
if(!is_numeric($b)) {
$str .= "\"".$b."\"";
} else {
$str .= $b;
}
if($id < count($ar)) {
$str .= ",";
}
}
$str .= "}";
return $str;
}
Then to use it:
<?php
$o = new mysqli(
"localhost",
"root",""
);
if($o->connect_error) {
echo "DUDE what are you/!";
} else {
$rz = mysqli_query($o,
"SELECT * FROM mydatabase.mytable"
);
$ar = noom($rz);
echo json($ar);
}
?>

Parsing SQL array data to php mail()

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

jQuery/Ajax - Post is not returning multiple results [duplicate]

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";
}

Returning MySql object with each row as array

I want to query my DB and get back an array of arrays. I'm getting all my rows merged into a flat array which makes parsing through it for my purposes very hard.
php:
function conn($sQuery){
$sMessage = '';
$db = new mysqli('localhost','root','','db') or die('unable to connect!');
if($db->connect_errno){
$message = $db->connect_error;
} else{
if($db->query($sQuery)){
$stmt = $db->prepare($sQuery);
$stmt->execute();
$oResult = $stmt->get_result();
while($rows = $oResult->fetch_assoc()){
foreach($rows As $value){
$aRows[] = $value;
}
}
$oResult->free();
$db->close();
return $aRows;
} else{
$sMessage = $db->error;
$db->close();
return $sMessage;
}
}
}
function requestNote(){
$sQuery = "SELECT * FROM `note` WHERE `sender_Id` = '" . $_SESSION['user_Id'] . "'";
$oResult = conn($sQuery);
if(!is_array($oResult)||!isset($oResult)||empty($oResult)||is_null($oResult)){
echo null;
} else{
echo json_encode($oResult);
}
}
js:
request.done(function(oResult){
var jsonResult = $.parseJSON(oResult);
console.log("Json returned: ", jsonResult);
});
This prints:
Json returned:
[1, 100000, 100000, "This is a test note inserted directly into DB", "2014-10-22 15:34:15", 2, 100000, 100000, "This is the second test ...serted directly into DB", "2014-10-22 21:56:50"]
What I want is:
Json returned:
[
[1, 100000, 100000, "This is a test note inserted directly into DB", "2014-10-22 15:34:15"],
[2, 100000, 100000, "This is the second test ...serted directly into DB", "2014-10-22 21:56:50"]
]
Replace
while($rows = $oResult->fetch_assoc()){
foreach($rows As $value){
$aRows[] = $value;
}
}
with
while($rows = $oResult->fetch_array(MYSQLI_NUM)) {
$aRows[] = $rows;
}
fetch_array(MYSQLI_NUM) will return a simple array instead of the associative, so that your json data will not have objects in it.
You don't need the foreach loop inside the while loop. The while iterates over the rows, so the foreach is then iterating over columns. It should just be:
while($rows = $oResult->fetch_assoc()){
$aRows[] = $rows;
}

Categories