Wrong output json_encode PHP - php

I am using this code to build an array and encode it to JSON.
while($row = mysqli_fetch_array($sql)) {
$results[] = array(
'wdatatype' => $row['wdatatype'],
'wdb' => $row['wdb'],
'wbyte' => $row['wbyte'],
'wbit' => $row['wbit'],
'bitval' => $row['bitval'],
);
}
$json = json_encode($results);
echo $json;
The output is this
[{"wdatatype":"DB","wdb":"100","wbyte":"0","wbit":"0","bitval":"1"}]
But for my jQuery script I need the output to be
{"wdatatype":"DB","wdb":"100","wbyte":"0","wbit":"0","bitval":"1"}
How do I accomplish this?
Thanks!

You're problem seems to stem from the fact that you're creating a multi-dimensional array. You're pushing an array as an element of the existing $results array. For you're desired output, $results should be an associative array, not an array of associative arrays.
Provided there is only one row in your result set, try this instead:
// Remove the while loop if you're only returning a single row
// such as with a LIMIT = 1 clause in your SQL statement.
$row = mysqli_fetch_array($sql);
// Push the single row as an array into $result
$results = array(
'wdatatype' => $row['wdatatype'],
'wdb' => $row['wdb'],
'wbyte' => $row['wbyte'],
'wbit' => $row['wbit'],
'bitval' => $row['bitval'],
);
// Now echo the json_encode
echo json_encode($results);
When converted using json_encode, the above will turn into a single object like so:
{"wdatatype":"DB","wdb":"100","wbyte":"0","wbit":"0","bitval":"1"}
rather than an array of objects.
Note: As #PankajGarg and #AmalMurali pointed out this should be used if you're only returning a single row. Failing to remove the while loop and returning a result set of more than one row will yield you a return of the last row only.
For a result set containing multiple rows, your current structure will work perfectly.
Alternatively as #Nilpo pointed out, you can simplify the above process by using mysqli_fetch_assoc() to return an associative array for you.
$row = mysqli_fetch_assoc($sql);
// Now echo the json_encode
echo json_encode($row);

Related

Convert MySQL to Json ResultSet

I'm trying to turn my results into a json encoded string. I know that now working on an external api seems a bit much, but I do think that it's something that will come in handy as times goes on. Currently, I use the following function:
//API Details
public function APIReturnMembers() {
$query = <<<SQL
SELECT uname
FROM {$this->tprefix}accounts
SQL;
$encode = array();
$resource = $this->db->db->prepare( $query );
$resource->execute();
foreach($resource as $row) {
$encode[] = $row;
}
echo json_encode($encode);
}
It does what it's supposed to as far as returning results go, e.g.:
[{"uname" : "guildemporium"}, {"uname" : "doxramos"}]
When I saw that I was ecstatic! I was on my way to implementing my own API that others could use later on as I actually got somewhere! Now of course I have hit a hickup. Testing my API.
To run the code to get the results I used
$api_member_roster = "https://guildemporium.net/api.php?query=members";
$file_contents = #file_get_contents($api_member_roster); // omit warnings
$memberRoster = json_decode($file_contents, true);
print_r($memberRoster);
The good news!
It works. I get a result back, yay!
Now the Bad.
My Result is
[
0 => ['uname' => 'guildemporium'],
1 => ['uname' => 'doxramos']
]
So I've got this nice little number integer interrupting my return so that I can't use my original idea
foreach($memberRoster as $member) {
echo $member->uname;
}
Where did this extra number come from? Has it come in to ruin my life or am I messing up with my first time playing with the idea of returning results to another member? Find out next time on the X-Files. Or if you already know the answer that'd be great too!
The numbered rows in the array as the array indices of the result set. If you use print_r($encode);exit; right before you use echo json_encode($encode); in your script, you should see the exact same output.
When you create a PHP array, by default all indices are numbered indexes starting from zero and incrementing. You can have mixed array indices of numbers and letters, although is it better (mostly for your own sanity) if you stick to using only numbered indices or natural case English indices, where you would use an array like you would an object, eg.
$arr = [
'foo' => 'bar',
'bar' => 'foo'
];
print_r($arr);
/*Array
(
[foo] => bar
[bar] => foo
)*/
$arr = [
'foo','bar'
];
/*Array
(
[0] => foo
[1] => bar
)*/
Notice the difference in output? As for your last question; no. This is normal and expected behaviour. Consumers will iterate over the array, most likely using foreach in PHP, or for (x in y) in other languages.
What you're doing is:
$arr = [
['abc','123']
];
Which gives you:
Array
(
[0] => Array
(
[0] => abc
[1] => 123
)
)
In order to use $member->foo($bar); you need to unserialize the json objects.
In you api itself, you can return the response in json object
In your api.php
function Execute($data){
// Db Connectivity
// query
$result = mysqli_query($db, $query);
if( mysqli_num_rows($result) > 0 ){
$response = ProcessDbData($result);
}else{
$response = array();
}
mysqli_free_result($result);
return $response;
}
function ProcessDbData($obj){
$result = array();
if(!empty($obj)){
while($row = mysqli_fetch_assoc($obj)){
$result[] = $row;
}
return $result;
}
return $result;
}
function Convert2Json($obj){
if(is_array($obj)){
return json_encode($obj);
}
return $obj;
}
Calling api.php
$result = $this->ExecuteCurl('api.php?query=members');
print_r($result);
here you $result will contain the json object

I want array in its original form

I created an array using PHP and Microsoft office access database using this code
Code:
<?php try{
$sql = "SELECT * FROM mcc ";
$result = $conn->query($sql);
$row = $result->fetchAll(PDO::FETCH_ASSOC);
print_r($row);
}catch(PDOExepction $e){
echo $e;
}?>
Output:
Array ( [0] => Array ( [sName] => Dihn [Name] => John Parker [BNE] => BOB DIHN ) )
Now I want to use this array for further operation like make an excel file and all but i cant because array contains []"Square brackets" ,"String without double quotation " ,"string with space" and no ","(comma) between two rows.
how can i simplify this code to use like normal array or any other suggestion.please help me
$row is an array (as PHP tells you in the output of print_r), so the array exists. print_r just outputs a more human-readable form of the array, that's exactly what the function was designed for. If you don't want that, then you are using the wrong function.
If you want to process the array using PHP, don't echo it, but use it directly, e.g. like this:
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
// Rows is an array of the results
foreach($rows as $row) {
$thename = $row['Name'];
// Do something with the data
}
If you want to output the array in valid PHP syntax, the easiest solution is to replace print_r with var_export:
$row = $result->fetchAll(PDO::FETCH_ASSOC);
var_export($row);
You did not give the slightest hint about how you want to process the output. However, if you want to process the output of your script, it might be easier to use JSON:
echo json_encode($row);

Referencing PHP arrays returned from MySQL for a JSON API

I have a result, $result, returned from an SQL query which contains the following data: [{"TOTAL":"12345"}]
I want to put that result into a JSON API with a route of, say, /api/total/ and have it return: {total:12345}. I'll be setting the first half of that manually, e.g. 'total' => whatever in the Slim framework.
$app->render(200, array(
'total' => $result["TOTAL"]
)
);
How do I reference 12345 from the returned array? Doing $result["TOTAL"] doesn't work.
The result looks like [{"TOTAL":"12345"}]?
So you have to json_decode it first.
$decodedResult = json_decode($result, true);
echo $decodedResult[0]['TOTAL'];
Use this code , you will get the value.
$result = '[{"TOTAL":"12345"}]';
$res = json_decode($result);
echo $res[0]->TOTAL;
Please try this
$res = json_decode($result);
even though there is only one object in the array, it is still an array so you need to reference the object's index.
$result[0]["TOTAL"]

store array in the database

I have three arrays example: $array1,$array2,$array3.
I want to insert the array2 and array3 in two different columns in the same table.
can i do that?
here is the code below that i am trying but it does not work for me i am doing in codeigniter:
controller:
$athletes_id = $this->input->post('athletes'); // array 1
$fields_id = $this->input->post('fields_id'); // array 2
$athlete_score = $this->input->post('athlete_score'); // array 3
$id = array();
foreach($athlete_score as $row){
$additional_data = array(
'test_reports_id' => $test_report_id,
'score' => $row,
);
$id[] = $this->test_model->save_test_reports_details($additional_data);
}
for($j=0;$j<count($fields_id);$j++){
$data2 = array('fields_id' => $fields_id[$j]);
$this->test_model->update_test_reports_details($id,$data2);
}
Model :
public function update_test_reports_details($id,$data2){
$this->db->where_in('id',$id);
$this->db->update('test_reports_details',$data2);
}
Just serialize the arrays.
$data2 = serialize($array2); // or whatever array you want to store
Then to retrieve with unserialize
$array2 = unserialize($data2);//or the row index
To store array in database you have to serialize it.
Try :
public function update_test_reports_details($id,$data2){
$this->db->where_in('id',$id);
$this->db->update('test_reports_details',serialize($data2));
}
To unserialize it when you get it from the database you have to use unserialize()
You can serialize as suggested in other answers, however I personally prefer to json_encode the array.
$data = json_encode($array);
And when you are reading in the model you should decode the data:
$array = json_decode($data, true); // set second argument to true to get an associative array
Using JSON has the advantage of better readability while still in the DB. This might not seem like much, but it can really help in some cases.

PHP json_encode return rows as arrays instead of objects

From my experience, when I json_encode data from a mysql table, the output is an object containing each row as an object within. What I want to do is to get each row as an array, like the example below (don't need the column names in there). How can I do that?
{ "Data": [
["1","Internet Explorer 4.0","Win 95+","4","X","1"],
["2","Internet Explorer 5.0","Win 95+","5","C","2"],
["3","Internet Explorer 5.5","Win 95+","5.5","A","3"],
["4","Internet Explorer 6","Win 98+","6","A","4"],
] }
Use mysql_fetch_row [docs] to get each row. This will get a row as a numerical array and those are also encoded as JSON arrays:
$data = array();
while(($row = mysql_fetch_row($result))) {
$data[] = $row;
}
echo json_encode(array('Data' => $data));
NOT CHECKED in interpreter:
You can change the type of variable by simple types convertion:
$data = DB::get('SELECT * FROM `table` WHERE 1');
echo json_encode(array('Data' => (array)$data));
Also you can use next function: array mysql_fetch_array ( resource $result [, int $result_type ] )

Categories