You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现多选下拉框及if条件中校验下拉选中值的方法

PHP多选下拉框实现方案

前端代码

多选下拉框需要给name属性添加[]后缀,才能让PHP后端接收到全部选中值的数组:

<!-- 多选课程下拉框 -->
<select name="corse_nm[]" multiple="multiple">
  <option value="all">全部课程</option>
  <option value="math">数学</option>
  <option value="chinese">语文</option>
  <option value="english">英语</option>
</select>

<!-- 分数下拉框(单选无需加[],多选同样加[]即可) -->
<select name="mrks_nm">
  <option value="0">全部分数</option>
  <option value="50">50分以上</option>
  <option value="-50">50分以下</option>
</select>
多选值校验与原有代码修复

原有代码问题说明

  1. 多选场景下$_POST['corse_nm']是数组类型,不能直接用==/!=做字符串比较
  2. 分支顺序逻辑错误:第二个分支$_POST['corse_nm'] != ''会优先触发,后面带分数判断的分支永远不会执行
  3. 存在赋值BUG:$_POST['corse_nm'] = 'isselected'是赋值操作,不是等值判断,应该用==
  4. 直接拼接SQL存在SQL注入风险,必须使用预处理语句规避

完整校验与查询实现

// 1. 基础参数接收与校验
$corse_nm = $_POST['corse_nm'] ?? [];
$mrks_nm = intval($_POST['mrks_nm'] ?? 0);
// 配置允许的课程值,避免非法值传入
$allowed_course = ['all', 'math', 'chinese', 'english'];

// 统一转换为数组兼容单选场景
if (!is_array($corse_nm)) {
    $corse_nm = (array)$corse_nm;
}
// 过滤空值和非法值
$corse_nm = array_filter($corse_nm);
$corse_nm = array_intersect($corse_nm, $allowed_course);
if (empty($corse_nm)) {
    $corse_nm = ['all']; // 无合法选中值时默认查全部
}

// 2. 动态拼接查询条件
$where = [];
$params = [];

// 处理课程条件
if (!in_array('all', $corse_nm)) {
    $placeholders = rtrim(str_repeat('?,', count($corse_nm)), ',');
    $where[] = "course IN ($placeholders)";
    $params = array_merge($params, $corse_nm);
}

// 处理分数条件
if ($mrks_nm > 0) {
    if ($mrks_nm == 50) {
        $where[] = "marks > 50";
    } elseif ($mrks_nm == -50) {
        $where[] = "marks < 50";
    }
}

// 3. 预处理执行SQL,避免注入
$sql = "SELECT * FROM regis";
if (!empty($where)) {
    $sql .= " WHERE " . implode(' AND ', $where);
}

$stmt = mysqli_prepare($conn, $sql);
if (!empty($params)) {
    $types = str_repeat('s', count($params));
    mysqli_stmt_bind_param($stmt, $types, ...$params);
}
mysqli_stmt_execute($stmt);
$sql_sel = mysqli_stmt_get_result($stmt);

内容的提问来源于stack exchange,提问作者user16982980

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 18:27:03