Getting back strange JSON array from MySQL - php

I have the following PHP code:
$data=mysql_query("SELECT * FROM notes WHERE rootNoteId='$noteId'");
$mainArray;
while($result = mysql_fetch_array($data))
{
$mainArray[]=$result;
}
$sendback = array(
"mainArray" => $mainArray
);
sendResponse(200, json_encode($sendback));
My table 'notes' has the following fields:
'noteId'
'authorName'
'noteBody'
However my return JSON string has the following format:
{
"0": "3",
"1": "Moe Bit",
"2": "Sub sub ",
"noteId": "3",
"authorName": "Moe Bit",
"noteBody": "Sub sub "
}
Why is it adding 0,1,2 indexes for the array with duplicate values of my table fields? I just want noteId, authorName, and noteBody-I'm not sure where it's coming up with "0","1","2".

mysql_fetch_array() in it's default "mode" fetches the result as associative & numeric array. So you get field names (what you want) and numeric indexes (the numbers you don't want).
To solve this pass the constant "MYSQL_ASSOC" as the second parameter to "mysql_fetch_array" or use the mysql_fetch_assoc() function.

try either mysql_fetch_assoc or mysql_fetch_object

Related

JSON object with array header

this question comes from the posting I found here:
DataTables Multiple Tables from Multiple JSON Arrays
I'd like to know the simplest and best way to generate the JSON below. I can see the pattern is 'JSON object -> Array Header -> Array -> JSON object' but I do not know how to do this in PHP, from a mySQLi query result. I imagine having a mySQL table with a 'policies' and 'services' column so the query might look something like:
Select name, id, score, type from myTable where type = 'policies' and
type = 'services'
And the result would come back something like:
name id score type
A 1 0 policies
B 2 0 services
But then how would I take that query and generate this JSON in php?
{
"Policies": [
{
"name": "A",
"id": "1",
"score": "0"
}
],
"Services": [
{
"name": "B",
"id": "2",
"score": "0"
}
]
}
Thanks for your help!
Start by creating the new empty array.
Then, iterate through the result and add it in the correct sub-array:
$new = [];
foreach ($result as $item) {
// Uppercase the first character
$type = ucfirst($item['type']);
if (!isset($new[$type])) {
// This type doesn't exist in the new array yet, let's create it.
$new[$type] = [];
}
// Add the item
$new[$type][] = $item;
}
// Output it as json
echo json_encode($new, JSON_PRETTY_PRINT);
The above code will also work if new types are added to the database.
PS. The JSON_PRETTY_PRINT argument is just to make the json string a bit more readable while developing. When everything looks good, you can remove it.

Excluding numbered-index elements of PDO::fetchAll()

$allrows = $pdo->fetchAll(); // select * from ....
I want to transform this $allrows into JSON by doing :
echo (json_encode($allrowl,JSON_PRETTY_PRINT));
My problem is that this fetchAll will not only extracting data as associate array but also indexed array for each element, hence repeating elements.
[
{
"org_id": "1",
"0": "1",
"category": "A",
"1": "A",
},
{
"org_id": "2",
"0": "2",
"category": "A",
"1": "A",
}
]
Thank you.
That's becuase the default fetch mode is FETCH_BOTH. CHange your mode to FETCH_ASSOC and you'll only get the non-numeric keys.
Assuming $pdo is a PDOStatement, set it like this prior to the fetch.
$pdo->setFetchMode(PDO::FETCH_ASSOC);
You can also set it in the fetch statement:
$pdo->fetchAll(PDO::FETCH_ASSOC);
Use PDO::FETCH_ASSOC to get only the associated arrays:
$allrows = $pdo->fetchAll(PDO::FETCH_ASSOC);

Create array from row objects in the same table :: PHP + SQL

I have an array like so
id | userID | item
1 ! 1 | {"property": 0, "property": "string"}
2 ! 1 | {"property": 4, "property": "string2"}
and I wish to return one array with like so:
[{
"property": 0,
"property": "string"
},
{
"property": 4,
"property": "string2"
}]
No matter what I try I cannot seem to get it to work properly. Either I get a whole string so number values get converted, or I get an object with \" everywhere. Currently I have this code
if ($query = $mysqli->query("SELECT item FROM userItems WHERE userID = 'id' "))
{
while ($row = $query->fetch_object())
{
$result->items[count($result)] = $row;
}
}
$test = stripslashes(json_encode($result->items));
which returns this ...
{"1":{"item":"{"property":"0","property":"string"}"}}
Been trying to solve it for hours and can't get it right
I tried your code and there're two main things:
you're building an array of associative arrays but associative array tends to overwrite identical associative keys with the latter in your code - in your case both keys are property,
the data you're retrieving from DB (userItems.item) already seems to be JSON encoded so you need to call json_decode() somewhere instead of calling json_encode() again; decoding your $row->item ($result->items[count($result)] = json_decode($row->item);) seems to do the trick.
Just as a sidenote you should consider wrapping your id parameter in SQL query into mysqli_real_escape_string() or so.
Let me know if that helped and you see the desired result now.

Excess JSON response

My JSON response seems to have excess keys in it. Any idea why?
Here is an excerpt from the JSON response:
{
"0": "1",
"id": "1",
"1": "XX University",
"name": "XX University",
"2": "http:\/\/ree.com\/images\/xxUniversity.png",
"backgroundImageUrl": "http:\/\/ree.com\/images\/XXUniversityLogo.png",
"3": "http:\/\/ree.com\/images\/xxUniversity.png",
"logoImageUrl": "http:\/\/ree.com\/images\/XXUniversityLogo.png"
},
Here is my PHP code:
$query = "SELECT * from $entity"; //Bad security,for a different question
$results = mysqli_query($con,$query);
//Parse to JSON
$json=array();
while($row=mysqli_fetch_array($results)){
$json[]=$row;
}
//Close connection
mysqli_close($con);
//Encode and send response as JSON (using the entity type as a parameter)
//echo json_encode(array($entity => $json), JSON_FORCE_OBJECT);
echo json_encode(array ($entity =>$json));
Your problem is mysqli_fetch_array. You want to pass MYSQLI_ASSOC as a second parameter.
while($row=mysqli_fetch_array($results,MYSQLI_ASSOC)){
$json[]=$row;
}
From the docs:
This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.
By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.
mysqli_fetch_array per default retrieves both numeric and named index.
You have to specify an additional parameters to get only the desired ones.
MYSQLI_ASSOC retrieves the named array,
MYSQLI_NUM retrieves just the integer indexed one
MYSQLI_BOTH retrieves both :)

How to echo JSON doubly nested object literal w/ proper "headers"

I'm trying to simply echo a JSON object literal which includes every row in my database table.
As standard with the methods found in many other similar questions I looked at, I'm fetching every row and encoding it like so:
$con=mysqli_connect("localhost","username","pass","markers");//markers is db table name
$result = mysqli_query($con,"SELECT * FROM markers");
$rows = array();
while($r = mysqli_fetch_array($result))
{
$rows[] = $r
//or: $rows[] = array('data' => $r);
}
echo json_encode($rows);
Similarly to the question PHP: can't encode json with multiple rows or mysql table to json ,
I want to echo a JSON Object which looks like this:
{
"data1": // how do I get "data1"?
{
name: John Smith,
title: Mr,
description: a man
}
}
{
"data2":{ // how do I get "data2"?
name:Bob Smith,
title: Mr,
description: another guy
}
}
Except I do not get how to achieve the "headers", the titles of the first level string of objects, such as "data1" or data2". In fact, my database table doesn't necessarily even have those values/that column.
This is what it looks like right now:
How can I get simply numerical "headers" like "1", "2" or "data1", "data2" without having to designate the "name" column as the "headers"? (Or do I have to have a column for that?)
My goal is to process the values in every "row" in the returned JSON.
I plan to use the jQ $.each function $.each(data, function(dataNum, dataInfo) -- e.g. data1 would be passed to dataNum and the values would be passed to dataInfo -- and be able to access specific table values by dataInfo.name, which right now is not working.
Thanks to any help in advance!
I would think you are way better off using mysqli_fetch_object() to get each row as it own object. When you then json_encode $rows you would have an array of objects.
Here is the code:
$con=mysqli_connect("localhost","username","pass","markers");//markers is db table name
$result = mysqli_query($con,"SELECT * FROM markers");
$rows = array();
while($r = mysqli_fetch_object($result))
{
$rows[] = $r;
}
echo json_encode($rows);
Your JSON would look like this:
[
{
"name":"Some Name",
"title":"Some Title",
"description":"Some description"
},
{
"name":"Some Other Name",
"title":"Some Other Title",
"description":"Some other description"
},
...
]
In javascript, that gives you an integer-indexed array of objects. So your javascript might look like this:
var array = JSON.parse(jsonString);
$.each(array, function(key, value) {
alert(key); // numerical index
alert(value.name); // name
alert(value.title); // title
alert(value.description); // description
});
Create indexes in your $rows variable:
<?php
$t['a'] = array ('name' => 'foo');
$t['b'] = array ('name' => 'bar');
echo json_encode ($t);
?>
In your case, a simple integer should do the trick, or something like $rows['data' . $i] followed by a $i++.

Categories