How can I fetch all the rows of the data? - php

I have this code in PHP:
if (empty($_GET)) {
$response['code'] = 1;
$response['status'] = $api_response_code[$response['code']]['HTTP Response'];
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc())
$response['data'] = $row;
} else
$response['data'] = NULL;
}
Currently, I am taking only the last row at $response['data']. How could I transform this code in order to get all the $row values?
I tried initializing $response['data'] = array();
and then did $this->response['data'] = $row;
but it didn't do the trick.
Please note that I am a begginer in PHP.

You are overwriting your $response['data'] with each iteration of the while fetch loop and not appending to the array. Hence, the last record is the only one retained.
Consider the following adjustment where $data is its own array to hold row records of the SQL query resultset. Then this entire array object can be appended to the initial $response array (creating a nested setup):
$i = 0;
$data = [];
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$data[$i] = $row;
...
$i++;
}
}
$response['data'] = $data;

Related

php while loop only showing last row in database

I'm trying to list all rows in the database (2 currently) in JSON format, but the only output I'm getting is the last row.
Output:
[{"id":"2","Name":"Googleplex","Address":"1600 Amphitheatre Pkwy, Mountain View, CA","Latitude":"37.421999","Longitude":"-122.083954"}]
Code:
if($status == "connected") {
$locations = $db->prepare('SELECT * FROM Locations');
$locations->execute();
$result = $locations->fetch(PDO::FETCH_ASSOC);
if(!empty($result)) {
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $locations->fetch(PDO::FETCH_ASSOC))
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
}
The problem is you're throwing away the first result you read in this line:
$result = $locations->fetch(PDO::FETCH_ASSOC);
You can just simplify your code to
if ($status == "connected") {
$locations = $db->prepare('SELECT * FROM Locations');
$locations->execute() or die("Unable to execute query");
$resultArray = array();
while ($row = $locations->fetch(PDO::FETCH_ASSOC)) {
$resultArray[] = $row;
}
echo json_encode($resultArray);
}

PHP Json response return the last row only

Hello i am trying to run this code lines with AngularJS but just get the last row of dataset, i have seen this example in a some sites, i don't know if i am missing some configuration:
$result = $mysqli->query ($query ) or die( $mysqli->error . __LINE__ );
$arr = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$arr['data'] = $row;
}
}
# JSON-encode the response
echo $json_response = json_encode($arr);
Thanks
This line is just overwriting $arr['data'] with the array $row:
$arr['data'] = $row;
Change it to
$arr['data'][] = $row;
and this will push the row, as an array, to $arr['data'].

PHP mysqli query result echo with foreach loop

in my last project I used foreach loop to assign to every mysqli result a variable, like $r->mydata, but I formatted my pc accidentally, so I lost my core file and I can't remember how exactly I did that. I remember that I did something like this
$result = $db->query("SELECT * FROM data");
if($result->num_rows){
while ($row = $result->fetch_object()) {
foreach ($row as $r){
$row[] = $r;
}
}
}
And I can access the result from outside the while loop like this:
<?php echo $r->mydata ?>
Can anyone edit my code so it will work like before?
it would be easier to use
$rows=$result->fetch_all(MYSQLI_ASSOC);
rather than looping through all the rows and building an array.
Maybe you don't remember how you did it, but if you did it once you should know at least which approach you followed to solve this, let help you to understand the code first:
$result = $db->query("SELECT * FROM data");
if($result->num_rows>0){
//iterating only if the table is not empty
while ($row = $result->fetch_object()) {
//Here you are iterating each row of the database
foreach ($row as $r){
//Here you are iterating each column as $r
//and (trying) adding it again to the $row array
$row[] = $r;
}
}
}
Why would you like to access to the $row outside the loop, if what you want to do is print each row, you can do it inside the loop:
$result = $db->query("SELECT * FROM data");
if($result->num_rows>0){
while ($row = $result->fetch_object()) {
foreach ($row as $r){
echo $r.'<br>';
}
}
}
If you do something like what follows, what part of the 'printed' data do you need? You may have been 'specializing' the result set by eliminating the rows to only use a single row...
$result = $db->query("SELECT * FROM data");
$r = new stdClass();
// Only loop if there is a result.
if ($result)
{
$r->myData = []; // You aren't exactly clear on 'myData'. In this instance, I am setting the rows inside of it.
while ($row = $result->fetch_object())
{
$r->myData[] = $row;
}
$result->close(); // Free result set
}
print_r($r->myData);
$records = array();
$result = $db->query("SELECT * FROM data");
if($result->num_rows){
while ($row = $result->fetch_object()) {
$records[] = $row;
foreach($records as $r);
}
}
and now you can access the result from any place in the page,example echo inside html h1:
<h1>My name is: <?php echo $r->name ?></h1>

importing mysql query result to json

i am trying to get data from remote mysql database and importing it to json
the connection is ok, the problem is that the result that finally echoed from json is not normal, this is my php code
<?php
require("config.inc.php");
$query = "Select * FROM comments";
$res = mysql_query($query);
$rows = mysql_fetch_assoc($res);
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["username"] = $row["username"];
$post["title"] = $row["title"];
$post["message"] = $row["message"];
//update our repsonse JSON data
array_push($response["posts"], $post);
}
// echoing JSON response
echo json_encode($response);
and this is the result echoed to the page:
{"success":1,"message":"Post Available!","posts":[{"username":"1","title":"1","message":"1"},{"username":"r","title":"r","message":"r"},{"username":"t","title":"t","message":"t"},{"username":"t","title":"t","message":"t"}]}
while my database table "comments" contain these data:
post_id username title message
1 reda test title 2 test message xxx
2 reda2 title 2 message 2
please help
thanks.
You are only returning 1 row / array by using
$rows = mysql_fetch_assoc($res);
So when you do
foreach ($rows as $row) {
you are trying to get a multidimensional array loop, from a single array. That is why each posts value is the 1st character from each column from the 1 returned row/array.
You need to build your $rows array. Try changing
$rows = mysql_fetch_assoc($res);
to
$rows = array();
while($result = mysql_fetch_assoc($res)){
$rows[] = $result;
}
You're not reading your result set from MySQL correctly. You're fetching just the first row and treating that as the entire results set. You need to loop, retrieving each row in turn.
Try this:
$query = "Select * FROM comments";
$res = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($res)!= 0) {
$response = array();
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["posts"] = array();
while ($row = mysql_fetch_assoc($res)) {
$post = array();
$post["username"] = $row["username"];
$post["title"] = $row["title"];
$post["message"] = $row["message"];
//update our repsonse JSON data
array_push($response["posts"], $post);
}
}
// echoing JSON response
echo json_encode($response);
Note: I haven't tested this code.
2nd Note - you shouldn't be using mysql_*() for new code - it's deprecated. Swicth to mysqli_*() or PDO.

Mysql query mysql_fetch_array

$data = mysql_query("SELECT * FROM users);
now the data is stored in the $data variable. I would like to store the mysql data in an array and return that.
$data_array = mysql_fetch_assoc($data);
This would store the first row (the first array) of the data.
now to store all the rows I was wondering what should I do.
The standard approach:
$res = mysql_query($sql);
$data = array();
while(($row = mysql_fetch_array($res)) !== false) {
$data[] = $row;
}
// now $data is an array with all rows
http://php.net/manual/en/function.mysql-fetch-array.php
Returns an array of strings that
corresponds to the fetched row, or
FALSE if there are no more rows.
This approach works with mysql_fetch_* functions.
while ($row = mysql_fetch_assoc($data))
{
array_push($data_array,$row);
}
If your result set is big, it's not a good idea to do that. It could use a lot of memory on the process.
Having said that, you could store the whole thing on an array like this:
<?php
$query="select * from table_xyz";
$result = mysql_query($query) or die(mysql_error());
$arr_table_result=mysql_fetch_full_result_array($result);
function mysql_fetch_full_result_array($result)
{
$table_result=array();
$r=0;
while($row = mysql_fetch_assoc($result)){
$arr_row=array();
$c=0;
while ($c < mysql_num_fields($result)) {
$col = mysql_fetch_field($result, $c);
$arr_row[$col -> name] = $row[$col -> name];
$c++;
}
$table_result[$r] = $arr_row;
$r++;
}
return $table_result;
}
?>
Got the code sample from the PHP site.
$res = mysql_query($sql);
$data = array();
while(($row[] = mysql_fetch_array($res)) !== false) {
}

Categories