Skip to content
Advertisement

echoing a result from the database with php only returns 1 result

I’m trying to get results from a database and return the data to my page.

I have 2 files, findtask, and functions. In functions I have some code that grabs all my data from the table. I then used a while loop to grab the stuff if I echo the results from the functions script it returns as it should id 1 2 and 3, my issue starts when trying to get the result from findtask script that only gets last result.

<?php
public function ShowOpenTasks ()
{
//i leave usersemail blank, because i only want tasks to show on this page if there not assigned.
    $query = "SELECT * FROM `tasks` WHERE `usersemail` = ''";
    if(!$result = mysqli_query($this->db, $query)) {
        exit(mysqli_error($this->db));
    }
    $data = [];
    if(mysqli_num_rows($result) > 0) {
        while($row = mysqli_fetch_assoc($result)) {
            $data = $row;
            echo $data['id'];
        }
    }
    return $data;
}
?>

My findtask page is

require __DIR__ . '/lib/functions.php';
$app = new FunctionClass();
$task = $app->ShowOpenTasks();
echo $task['id'] //id being the name of the id table of the task. 

This one will only turn the last id for some reason.

What is wrong and how can this be fixed?

Advertisement

Answer

It will only return last id since you are setting data to equal row

$data = $row;

So each row you replace it with the last one.

I guess you want an array instead, so you could do:

$data[] = $row;

then to print out all tasks:

$task = $app->ShowOpenTasks();
print_r($task);

This would give you an array of results.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement