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

如何创建可搜索MySQL数据库的下拉菜单,并将选中值代入查询?

解决方案

你现有代码存在两处属性配置错误,导致下拉选中值无法正常提交到后端,先修正前端表单代码:

  • name属性需要加在<select>标签上,而不是默认选中的<option>标签上
  • <label>标签不要嵌套在<select>内部,且for属性要和<select>的id对应

修正后前端代码

<form class="form-horizontal" action="search_keyword.php" method="get">
  <fieldset>
    <label class="col-md-4 control-label" for="searchinput">Analysegegenstand</label>
    <select id="searchinput" name="type_select">
      <option disabled selected>Analysegegenstand wählen</option>
      <?php
          include "db_connect.php";
          
          $records = mysqli_query($mysqli, "SELECT Analysegegenstand From Analysegegenstand"); 

          while($data = mysqli_fetch_array($records))
          {
              // 加htmlspecialchars避免XSS风险,特殊字符也能正常展示
              echo "<option value='". htmlspecialchars($data['Analysegegenstand']) ."'>" . htmlspecialchars($data['Analysegegenstand']) ."</option>"; 
          }   
      ?>  
    </select>
  </fieldset>
  <button type="submit" class="btn btn-primary">提交搜索</button>
</form>

后端search_keyword.php查询逻辑

直接用$_GET接收下拉提交的选中值,使用预处理语句执行查询,避免SQL注入风险:

<?php
include "db_connect.php";

// 接收下拉选中值,提交方式为post的话替换成$_POST['type_select']
$selected_type = $_GET['type_select'] ?? '';

// 基础参数校验
if (empty($selected_type)) {
    die("请先选择分析对象");
}

// 预处理查询,把下面的表名和查询字段替换成你实际业务需要的内容
$stmt = $mysqli->prepare("SELECT * FROM 你的业务表名 WHERE Analysegegenstand = ?");
$stmt->bind_param("s", $selected_type);
$stmt->execute();
$result = $stmt->get_result();

// 遍历输出查询结果
while ($row = $result->fetch_assoc()) {
    // 这里写你自己的结果展示逻辑
    var_dump($row);
}

// 释放资源
$stmt->close();
$mysqli->close();
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 07:15:03