PHP why does this only output 1 row? - php

$responses = array();
while ($row = mysql_fetch_array($result)) {
$response = array(
'name' => $row['name']
);
$row;
$responses['name5'] = $response;
}
echo json_encode($responses);
I'm currently only getting 1 rows from this statement I know for a fact their are more.

On each iteration of your while loop, you are overwriting the same array key $responses['name5'], so in the end you'll only have one value in the $responses array.
Instead, you might want something like this to append to the end of the array:
$responses[] = $response;

you are overwriting the $response variable that's why, array_push instead

$responses['name5'] = $response;
You will get only last row because you replace your data each cycle step.
Try this:
$responses['name5'][] = $response;

Because you're resetting the $response array to a single array in the loop. You want to add to the array.
$responses = array();
while ($row = mysql_fetch_array($result)) {
array_push($response, array(
'name' => $row['name']
));
$row;
$responses['name5'] = $response;
}
echo json_encode($responses);

do
$responses[] = array('name5' => $response);

Related

Push array into array then encode - PHP

I'm trying to combine a few mySQL queries in a single PHP and push it all into a single JSON object.
So, I'm starting with the first query...like this:
$data=[];
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);
$final_count = count($response);
$data['count'] = $final_count;
If I then do echo json_encode($data); I get a nicely formatted object like: {"count":61}
I then have a second query that I put the results through a loop, like so:
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);
$items = array();
foreach ($response as &$value) {
$items[] = $value['date_added'];
}
echo json_encode($items);
And I get my nice set of dates:
["2017-06-24 00:08:58","2017-06-26 15:01:48","2017-06-27 15:01:48","2017-06-28 23:19:41","2017-06-29 01:38:07","2017-06-30 00:08:58"]
Here's the question, how do I get this all back together like so:
{
"count": 61,
"dates": [
"2017-06-24 00:08:58",
"2017-06-26 15:01:48",
"2017-06-27 15:01:48",
"2017-06-28 23:19:41",
"2017-06-29 01:38:07",
"2017-06-30 00:08:58"
]
}
You could use
$myData['count'] = $final_count;
$myData['dates'] = $items
echo json_encode($myData);
$data=[];
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);
$final_count = count($response);
// first store count in `$data`
$data['count'] = $final_count;
$data['dates'] = [];
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);
// next, store dates in subarray of `$data`
foreach ($response as &$value) {
$data['dates'][] = $value['date_added'];
}
// finally encode everything
echo json_encode($data);
Of course you can use array_merge of all your collected data.
Or:
$data=[];
// get $final_count
$data['count'] = $final_count;
// ... do some more stuff
// load items from db
$data['dates'] = $items;
echo json_encode($data);

PHP While loop for Select Query

Can anyone explain me how to get the final value assigned to variable after completing executing while loop?
In my below code I wanted to echo the response out of while loop after fetching all the values from the rows.
Because if I put echo out of while loop it only shows 1st record.
while ($row = oci_fetch_array($array)) {
$response = $row['0']->load();
echo $response;
}
You will get the last rows value into the $response.
Cause: Every time the loop executes will assign value into the variable. But as you echo it you can see all the values as output.
So what you really need to do is storing the values in an array...
$response = array();
while ($row = oci_fetch_array($array)) {
$response[] = $row['0']->load();
}
print_r($response);
If you need further information about this , just let me know.
Since you are doing variable assignment and echo inside while loop, it will not serve your purpose.
You have to do it like below:-
$response = array(); // create an array
while ($row = oci_fetch_array($array)) {
$response[] = $row['0']->load(); // assign each value to array
}
echo "<pre/>";print_r($response);// print the array
Note:- this array will have all the values now. You can manipulate it in your desired way.Thanks
while ($row = oci_fetch_array($array)) {
$response = $row['0']->load();
}
echo $response;
Try this:
$response = [];
while ($row = oci_fetch_array($array)) {
$response[] = $row['0']->load();
}
var_dump($response);

PHP index array for JSON

Looking for some help.. Don't know the best approach to this issue...
I'm pushing a new reference onto an array but the "true" value is being inserted with quotes, which fails my json format.
while( $row = mysqli_fetch_assoc($res) ) {
if($row['id']=="2"){
$row['children']= 'true';
}
$data[] = $row;
}
echo json_encode( $data);
Outputs
[{"id":"2","name":"john","text":"john","parent_id":"0","children":"true"}]
When i need...
{"id":"2","name":"john","text":"john","parent_id":"0","children":true}]
How would i go about removing the qoutes or inserting it correctly first.??
If you want the 'children' to be boolean then set it to boolean.
while( $row = mysqli_fetch_assoc($res) ) {
if($row['id']=="2"){
$row['children'] = true;
}
$data[] = $row;
}
echo json_encode( $data);

Json encode an entire mysql result set

I want to get json with php encode function like the following
<?php
require "../classes/database.php";
$database = new database();
header("content-type: application/json");
$result = $database->get_by_name($_POST['q']); //$_POST['searchValue']
echo '{"results":[';
if($result)
{
$i = 1;
while($row = mysql_fetch_array($result))
{
if(count($row) > 1)
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
echo ",";
}
else
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
}
$i++;
}
}
else
{
$value = "FALSE";
echo json_encode(array('id'=>1, 'name' => "")); // output the json code
}
echo "]}";
i want the output json to be something like that
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]}
but the output json is look like the following
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"},]}
As you realize that there is comma at the end, i want to remove it so it can be right json syntax, if i removed the echo ","; when there's more than one result the json will generate like this {"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]} and that syntax is wrong too
Hope that everybody got what i mean here, any ideas would be appreciated
If I were you, I would not json_encode each individual array, but merge the arrays together and then json_encode the merged array at the end. Below is an example using 5.4's short array syntax:
$out = [];
while(...) {
$out[] = [ 'id' => $i, 'name' => $row['name'] ];
}
echo json_encode($out);
Do the json_encoding as the LAST step. Build your data structure purely in PHP, then encode that structure at the end. Doing intermediate encodings means you're basically building your own json string, which is always going to be tricky and most likely "broken".
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = array('id'=>$i, 'name' => $row['name']);
}
echo json_encode($data);
build it all into an array first, then encode the whole thing in one go:
$outputdata = array();
while($row = mysql_fetch_array($result)) {
$outputdata[] = $row;
}
echo json_encode($outputdata);

json not giving back the proper result from database array

I am getting back two rows from my query, I tested it in phpadmin.
In firebug I can only see the data from one row.
What could be wrong that I don't see?
$data = mysql_fetch_assoc($r);
}
}
header('Content-type: application/json');
$output = array(
"check" => $check,
"users" => $data,
"testnumberoffrows" => $number
);
echo json_encode($output);
in the ajaxfunction
if( data.check ){
var user = data.users;
console.log(user);
thanks, Richard
mysql_fetch_assoc() fetches only one row. You need to loop until it returns FALSE, building up an output array.
Something like this:
while (($row = mysql_fetch_assoc($r)) !== FALSE) {
$data[] = $row;
}
Please try
$got=array();
while ($row = mysql_fetch_array($r)) {
array_push($got, $row);
}
mysql_free_result($r);
header('Content-type: application/json');
$output = array(
"check" => $check,
"users" => $data,
"testnumberoffrows" => $number
);
echo json_encode($output);

Categories