I'm working on a booking system and I want my users to be able to see their bookings. I'm using a foreach loop to echo all the bookings. However, the last two columns have a 0-1 value and I want to echo something else based on that value or hide something altogether.
Here's the loop:
while ($row = $result->fetch_assoc()) {
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
}
And here are the conditions:
if($row['status']== 'To pay'){
echo '<td>
<form action="./payments/index.php" method="post">
<button type="submit" name="submit" style="background: linear-gradient(-145deg, rgba(255, 216, 133,1) 0%, rgba(245, 164, 37,1) 100%);">Pay Now!</button>
</form>
</td>';
}else{
echo '<th>Paid</th>';
}
if($row['modified']=='no'){
echo '<td>';
echo '<form action="modify.php?id='.$row['Id'].'" method="post">
<button id="myBtnM" type="submit" name="submit" style="background: linear-gradient(-145deg, rgba(255, 216, 133,1) 0%, rgba(245, 164, 37,1) 100%);">Modify</button>
</form>';
echo '</td>';
echo '<td>';
echo '<form action="cancel.php" method="post">
<button id="myBtnC" type="submit" name="submit" onclick="return checkDelete()" style="background: linear-gradient(-145deg, rgba(255, 216, 133,1) 0%, rgba(245, 164, 37,1) 100%);">Cancel</button>
</form>';
echo '</td>';
}
So, the loop works, but the if statement only echoes one row. I tried everything I could think of, but I'm a beginner and I can find a solution. If I add the if statement inside the loop, it echoes one entry forever. Same if it is inside the while loop only. I search on here and google, but I couldn't find anything that helps. If this has been answered already, please point me towards it, and my apologies.
CodePudding user response:
Test the column name in the loop so you can use the special code for the status
and modified
columns.
while ($row = $result->fetch_assoc()) {
echo "<tr>";
foreach ($row as $key => $value) {
if ($key == 'status') {
if($value == 'To pay'){
echo '<td>
<form action="./payments/index.php" method="post">
<button type="submit" name="submit" style="background: linear-gradient(-145deg, rgba(255, 216, 133,1) 0%, rgba(245, 164, 37,1) 100%);">Pay Now!</button>
</form>
</td>';
}else{
echo '<th>Paid</th>';
}
} elseif ($key == 'modified') {
if ($value == 'no') {
echo '<td>';
echo '<form action="modify.php?id='.$row['Id'].'" method="post">
<button id="myBtnM" type="submit" name="submit" style="background: linear-gradient(-145deg, rgba(255, 216, 133,1) 0%, rgba(245, 164, 37,1) 100%);">Modify</button>
</form>';
echo '</td>';
echo '<td>';
echo '<form action="cancel.php" method="post">
<button id="myBtnC" type="submit" name="submit" onclick="return checkDelete()" style="background: linear-gradient(-145deg, rgba(255, 216, 133,1) 0%, rgba(245, 164, 37,1) 100%);">Cancel</button>
</form>';
echo '</td>';
}
} else {
echo "<td>" . $value . "</td>";
}
}
}