
本文介绍如何在 php + mysql 构建的简易工单系统中,依据数据库查询出的“进度状态”字段(如 done、in-progress、not done),自动为表格每一行添加对应 css 类,实现可视化状态着色。
本文介绍如何在 php + mysql 构建的简易工单系统中,依据数据库查询出的“进度状态”字段(如 done、in-progress、not done),自动为表格每一行添加对应 css 类,实现可视化状态着色。
在维修工单这类轻量级管理系统中,通过颜色直观反映任务状态(如绿色表示已完成、黄色表示进行中、红色表示未开始/超期)能显著提升运维效率。实现该效果的关键在于:将数据库中的状态值映射为预定义的 CSS 类名,并在 PHP 循环输出表格行时动态绑定。
✅ 步骤一:定义语义化 CSS 类
在 <style></style> 标签或外部 CSS 文件中声明清晰、可维护的状态样式:
.done {
background-color: #d4edda; /* 柔和绿色 */
color: #155724;
}
.inprogress {
background-color: #fff3cd; /* 柔和黄色 */
color: #856404;
}
.notdone {
background-color: #f8d7da; /* 柔和红色 */
color: #721c24;
}? 建议使用浅色背景而非纯色(如
#00ff00),避免视觉疲劳;同时设置文字颜色确保可读性。
✅ 步骤二:PHP 动态绑定 class 属性
假设你已通过 PDO 或 MySQLi 查询出结果集 $result,在遍历数据时判断 status 字段并生成对应类名:
立即学习“前端免费学习笔记(深入)”;
<table border="1" class="status-table">
<thead>
<tr>
<th>客户姓名</th>
<th>设备型号</th>
<th>当前状态</th>
<th>最后更新</th>
</tr>
</thead>
<tbody>
<?php while ($row = $result->fetch_assoc()): ?>
<?php
// 根据数据库字段值映射 CSS 类
switch (trim($row['status'])) {
case 'Done':
$rowClass = 'done';
break;
case 'In-Progress':
case 'In Progress':
$rowClass = 'inprogress';
break;
default:
$rowClass = 'notdone';
}
?>
<tr class="<?= htmlspecialchars($rowClass) ?>">
<td><?= htmlspecialchars($row['customer_name']) ?></td>
<td><?= htmlspecialchars($row['device_model']) ?></td>
<td><?= htmlspecialchars($row['status']) ?></td>
<td><?= date('Y-m-d H:i', strtotime($row['updated_at'])) ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>⚠️ 注意事项:
- 使用
htmlspecialchars()防止 XSS 攻击(尤其当字段内容来自用户输入);trim()处理可能存在的空格导致匹配失败;switch比嵌套if-else更易扩展新状态(如新增'On-Hold' => 'hold');- 状态字段名(如
'status')需与数据库实际列名一致。
✅ 可选增强:前端动态更新(无需刷新)
若需在页面内实时更改状态并立即变色,可结合 AJAX + jQuery:
// 点击状态单元格切换状态(示例)
$('td[data-status]').on('click', function() {
const $td = $(this);
const currentStatus = $td.data('status');
const newStatus = currentStatus === 'Done' ? 'In-Progress' :
currentStatus === 'In-Progress' ? 'Not Done' : 'Done';
// 发送更新请求(后端需提供 /update-status.php 接口)
$.post('update-status.php', {
id: $td.data('id'),
status: newStatus
}, function() {
$td.text(newStatus).data('status', newStatus);
$td.closest('tr').attr('class', newStatus.toLowerCase().replace(/-/g, '')); // 同步 class
});
});✅ 总结
该方案不依赖 JavaScript 即可完成服务端渲染着色,兼顾性能与兼容性;核心逻辑简洁明确:状态值 → 类名 → CSS 样式。后续如需增加更多状态(如 Cancelled、Delayed),只需扩展 CSS 类与 PHP 映射逻辑即可,无需修改 HTML 结构或 JS 行为,具备良好的可维护性与可扩展性。



















