PHP+MySQL实现检测记录存在时更改select下拉选项背景色
实现方案
提供两种适配不同场景的实现方式:
方案1:服务端直接渲染(页面加载时已确定查询日期$date)
适合查询日期固定、不需要用户动态选择日期的场景,直接在渲染页面时判断状态,不需要额外前端请求。
步骤1:先查询指定日期所有已预约的时间段
<?php // 此处$date为你要查询的预约日期 $reservedHours = []; // 使用预处理语句避免SQL注入,比原直接拼接SQL的写法更安全 $stmt = mysqli_prepare($cn, "SELECT ora_inizio FROM prenotazioni WHERE data = ?"); mysqli_stmt_bind_param($stmt, "s", $date); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); while($row = mysqli_fetch_assoc($result)){ $reservedHours[] = $row['ora_inizio']; } mysqli_stmt_close($stmt); ?>
步骤2:渲染下拉选项时判断添加样式
<select name="time_slot" id="time_slot"> <?php // 定义所有可选时间段 $timeOptions = ['9:00','9:15','9:30','9:45','10:00','10:15','10:30','10:45','11:00']; foreach($timeOptions as $hour): $isReserved = in_array($hour, $reservedHours); ?> <option value="<?php echo $hour; ?>" <?php if($isReserved) echo 'style="background-color: #ff0000; color: #ffffff;"'; ?> > <?php echo $hour; ?> </option> <?php endforeach; ?> </select>
方案2:AJAX异步查询(日期由用户动态选择场景)
适合用户先选日期、再加载对应日期预约状态的场景,无需刷新页面即可更新下拉选项样式。
步骤1:编写后端查询接口check_reserved.php
<?php // 自行引入数据库连接配置 header('Content-Type: application/json'); $date = $_POST['date'] ?? ''; if(empty($date)){ echo json_encode(['reserved' => []]); exit; } $reservedHours = []; $stmt = mysqli_prepare($cn, "SELECT ora_inizio FROM prenotazioni WHERE data = ?"); mysqli_stmt_bind_param($stmt, "s", $date); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); while($row = mysqli_fetch_assoc($result)){ $reservedHours[] = $row['ora_inizio']; } echo json_encode(['reserved' => $reservedHours]); mysqli_stmt_close($stmt); ?>
步骤2:添加前端交互逻辑
// 假设日期选择框id为select_date,时间段下拉框id为time_slot document.querySelector('#select_date').addEventListener('change', function(){ const selectedDate = this.value; fetch('check_reserved.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: 'date=' + encodeURIComponent(selectedDate) }) .then(res => res.json()) .then(data => { const reservedList = data.reserved; // 遍历所有时间段选项更新样式 document.querySelectorAll('#time_slot option').forEach(option => { option.style.backgroundColor = 'unset'; option.style.color = 'unset'; if(reservedList.includes(option.value)){ option.style.backgroundColor = 'red'; option.style.color = '#fff'; // 可选配置:禁用已预约选项,防止用户选中 // option.disabled = true; } }) }) })
注意事项
- 原示例代码直接拼接SQL变量存在SQL注入风险,必须替换为预处理语句的写法,避免数据库安全问题。
- 可根据业务需求调整红色的色值、或者添加已预约选项禁用的逻辑。
内容的提问来源于stack exchange,提问作者Gabriele Morreale
相关产品推荐
相关产品推荐

