Reputation: 828
I have a PHP class that fetches data from a database and another class that displays the fetched data. The code seems to be fine except that instead of displaying all the rows, it displays only what is supposed to be the last row in the result. here is the code that fetches data
$getComm->execute();
$result = $getComm->fetchALL(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$_SESSION['days'] = $row['sales_day'];
$_SESSION['amount'] = $row['sales_total'];
$_SESSION['commission'] = $row['sales_comm'];
}
And this is the code that displays the data
<tr>
<td><label><?php echo $_SESSION['days']; ?></label></td>
<td><label><?php echo $_SESSION['amount']; ?></label></td>
<td><label><?php echo $_SESSION['commission']; ?></label></td>
</tr>
The only problem is that the last row is displayed instead of all the rows in the query.
Upvotes: 0
Views: 800
Reputation: 719
You are supposed to wrap the table in the loop.
Right now you run the loop and keep overwriting the same session value and then you are using that session variable which holds the last overwritten value.
You have to do somethings like this-
<?php foreach ($result as $row) { ?>
<tr>
<td><label><?php echo $row['sales_day']; ?></label></td>
<td><label><?php echo $row['sales_total']; ?></label></td>
<td><label><?php echo $row['sales_comm']; ?></label></td>
</tr>
<?php } ?>
I am not sure why would you do it with sessions? If you simply want to display the rows you can do as I suggested. But if you want to store all that data into session then you do that by storing an array into the session like this-
$i=0;
foreach ($result as $row) {
$_SESSION['days'][$i] = $row['sales_day'];
$_SESSION['amount'][$i] = $row['sales_total'];
$_SESSION['commission'][$i] = $row['sales_comm'];
$i++;
}
Upvotes: 1
Reputation: 138
in your loop every time SESSION with same name get different value, every time previously value will be lost. you can create array then all row insert in array and session be equal to array because you have many values for one session name.
$days = array();
$amounts = array();
$commissions = array();
foreach ($result as $row) {
array_push($days,$row['sales_day']);
array_push($amounts,$row['sales_total']);
array_push($commissions, $row['sales_comm']);
}
$_SESSION['days'] = $days;
$_SESSION['amount'] = $amounts;
$_SESSION['commission'] = $commissions;
Upvotes: 4
Reputation: 145
I can't comment due to not enough rep, so I'll have to write this as an answer.
To me it looks fine, I would think there is not data in $row['sales_day'] and $row['sales_total'].
Have you checked your database query is correct? also have you tried on the page you perform your foreach loop to echo $row['sales_day'] or $row['sales_total'] directly to see if it holds data?
Edit: I noticed you write fetchAll with two capital L's as: "fetchALL". Not sure it makes a difference but looking through PHP manual, it should be written as "fetchAll"
Upvotes: 0