Reputation: 3
I am pulling data from my mySQL database and outputting it onto my page fine, however, I want to style specific data on the page using Bootstrap. I've tried to write functions to pull the data separately, but I'm sure I'm doing something wrong.
This is for a simple CRUD database using PHP and mySQL, styled with Bootstrap 4 and JQuery. I've tried to write a function within the page in place of $row[status]
, but I think I'm missing a step.
The table should output either "EXP"
or "PAID"
under $row["status"]
.
<?php if (isset($_POST['submit'])) {
if ($result && $statement->rowCount() > 0) { ?>
<h2>Results</h2>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $row) { ?>
<tr>
<td><?php echo escape($row["id"]); ?></td>
<td><?php echo escape($row["status"]); ?></td>
<td><a class="btn btn-warning" href="update-single.php?id=<?php echo escape($row["id"]); ?>">Edit</a></td>
</tr>
<?php } ?>
</tbody>
</table>
If the $row["status"]
from the table = "EXP"
I want to wrap it with a span HTML
example: <span class="badge badge-danger"> </span>
to wrap, else if it's "PAID"
<span class="badge badge-success"> </span>
gets wrapped around "PAID"
Upvotes: 0
Views: 49
Reputation: 3225
Assuming status
have only 2 possible values: EXP
or PAID
.
You could modify the table cell like this:
<td><span class="badge badge-<?php echo $row["status"] == "EXP" ? 'danger' : 'success' ?>"><?php echo escape($row["status"]); ?></span></td>
Upvotes: 0
Reputation: 316
Perhaps this is what you're looking for?
I've wrapped your span as required and made it a bit more readable with the ":" notation instead of curly brackets
<?php if (isset($_POST['submit'])): ?>
<?php if ($result && $statement->rowCount() > 0): ?>
<h2>Results</h2>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $row) { ?>
<tr>
<td><?php echo escape($row["id"]); ?></td>
<?php if ($row["status"] === "EXP"): ?>
<td><span class="badge badge-danger"><?php echo escape($row["status"]); ?></span></td>
<?php elseif ($row["status"] === "PAID"): ?>
<td><span class="badge badge-success"><?php echo escape($row["status"]); ?></span></td>
<?php endif: ?>
<td><a class="btn btn-warning" href="update-single.php?id=<?php echo escape($row["id"]); ?>">Edit</a></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
<?php endif; ?>
If duplicating HTML isn't your thing. You can use a variable in the loop and switch the badge-{name}
class name to your liking.
Upvotes: 0
Reputation:
replace <td><?php echo escape($row["status"]); ?></td>
with:
<td>
<?php
if($row["status"]=='EXP'){//assumes exp and paid are only option otherwise use an elseif
echo '<span class="badge badge-danger">';
}else{
echo '<span class="badge badge-success">';
}
echo escape($row["status"]).'</span>';
?>
</td>
Upvotes: 1