php while loop only showing last row in database - php

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

Related

How modify to PHP SQL SELECT query to display message depending on if data is found

I have the following SELECT query that shows data depending on if it exists in the mySQL table.
Right now if it does it will display all of the records found, If not it will just display nothing.
I would like to make it display if the record is found
{"error":false}
and If the record is not found
{"error":true}
The following is what I have so far:
$sql = "SELECT field1,field2
from Table1 WHERE field3 = 'Dog' ";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// Create temporary connection
$resultArray = array();
$tempArray = array();
// Look through each row
while($row = $result->fetch_object())
{
// 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);
}
mysqli_close($con);
How can this be achieved?
you need to initialize an array with a default value, then change the value if the records are found
$sql = "SELECT field1,field2
from Table1 WHERE field3 = 'Dog' ";
$resultArray = ['error' => true];
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// Create temporary connection
$tempArray = array();
// Look through each row
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
$resultArray['error'] = false;
}
echo json_encode($resultArray);
mysqli_close($con);
You can do something like that:
$return = [
'error' => true
];
$sql = "SELECT field1,field2
from Table1 WHERE field3 = 'Dog' ";
$result = mysqli_query($con, $sql);
if($result && $result->num_rows > 0){
$return['error'] = false;
}
mysqli_close($con);
echo json_encode($return);

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'].

How can I fetch all the rows of the data?

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;

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>

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