如何用PHP+MySQLi实现表格不同Status状态的行/单元格样式区分
动态给表格状态字段设置不同样式的实现方法
这事儿其实挺简单的,核心就是在遍历数据库返回的结果时,根据status字段的值动态给对应的<td>(甚至整行<tr>)设置不同的样式就行。我给你两种实用的实现方案,你可以按需选择:
方案1:直接使用内联样式(快速实现)
这种方式不需要额外写CSS,直接在输出<td>的时候通过if-else判断设置style属性:
<?php require_once 'config.php'; $sql = "SELECT * FROM retail"; if($result = mysqli_query($link, $sql)){ if(mysqli_num_rows($result) > 0){ echo "<table border='1' cellpadding='8' cellspacing='0'>"; echo "<tr>"; echo "<th>ID</th>"; echo "<th>名称</th>"; echo "<th>状态</th>"; // 其他表头字段自行补充 echo "</tr>"; while($row = mysqli_fetch_array($result)){ echo "<tr>"; echo "<td>" . htmlspecialchars($row['id']) . "</td>"; echo "<td>" . htmlspecialchars($row['name']) . "</td>"; // 核心判断逻辑 if($row['status'] === 'DEACTIVE'){ // 给DEACTIVE设置红色背景+深色文字 echo "<td style='background-color: #f8d7da; color: #721c24; font-weight: 500;'>" . htmlspecialchars($row['status']) . "</td>"; } else { // 给ACTIVE设置绿色背景+深色文字 echo "<td style='background-color: #d4edda; color: #155724; font-weight: 500;'>" . htmlspecialchars($row['status']) . "</td>"; } // 其他字段输出 echo "<td>" . htmlspecialchars($row['other_field']) . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_free_result($result); } else { echo "没有找到匹配的记录"; } } else { echo "查询失败: " . mysqli_error($link); } mysqli_close($link); ?>
方案2:使用CSS类(更易维护)
如果后续需要修改样式,或者状态类型可能扩展,用CSS类的方式更灵活,也更符合代码规范:
首先在页面头部添加CSS样式:
<style> /* 表格基础样式 */ table { border-collapse: collapse; width: 80%; margin: 20px 0; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } /* 状态样式类 */ .status-active { background-color: #d4edda; color: #155724; font-weight: 500; } .status-deactive { background-color: #f8d7da; color: #721c24; font-weight: 500; } </style>
然后PHP部分通过三元运算符(或者if-else)动态添加类名:
<?php require_once 'config.php'; $sql = "SELECT * FROM retail"; if($result = mysqli_query($link, $sql)){ if(mysqli_num_rows($result) > 0){ echo "<table>"; echo "<tr>"; echo "<th>ID</th>"; echo "<th>名称</th>"; echo "<th>状态</th>"; // 其他表头字段 echo "</tr>"; while($row = mysqli_fetch_array($result)){ // 动态判断并设置样式类 $statusClass = ($row['status'] === 'DEACTIVE') ? 'status-deactive' : 'status-active'; echo "<tr>"; echo "<td>" . htmlspecialchars($row['id']) . "</td>"; echo "<td>" . htmlspecialchars($row['name']) . "</td>"; echo "<td class='$statusClass'>" . htmlspecialchars($row['status']) . "</td>"; echo "<td>" . htmlspecialchars($row['other_field']) . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_free_result($result); } else { echo "没有找到匹配的记录"; } } else { echo "查询失败: " . mysqli_error($link); } mysqli_close($link); ?>
几个小提醒:
- 一定要用
htmlspecialchars()转义输出的内容,防止XSS攻击,尤其是当status字段可能被用户输入修改的情况下; - 判断时用严格相等
===,避免因为类型转换导致的意外问题; - 如果需要给整行设置样式,只需要把
$statusClass加到<tr>标签上就行,比如echo "<tr class='$statusClass'>";。
内容的提问来源于stack exchange,提问作者kavitha
相关产品推荐
相关产品推荐

