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

如何从动态生成的单选框获取数据并提交到数据库

解决动态单选组的宾客出席数据收集问题

第一步:修改表单的单选框命名逻辑

原来的单选框命名无法直接关联宾客姓名,我们可以把单选框的name改成数组格式,直接绑定宾客姓名,让提交的数据能对应到具体的人:

<?php foreach ($results as $result){ 

  $party = $result['party']; // 数据库中为varchar类型,值为"John, Doe" 
  $party_guests = explode(",", $party);

  foreach ($party_guests as $index=>$guest){ 
      $clean_guest = trim($guest); // 去除姓名前后多余空格
  ?>

  <span class="guest__name"><?php echo $clean_guest; ?></span>
  <div class="guest__options-option">
    <span>Attending?</span>
    <div class="guest__options-group">
      <input class="guest__attendance-input" id="attending-yes-<?php echo $index; ?>" type="radio" name="attending[<?php echo htmlspecialchars($clean_guest); ?>]" value="yes" required/>
      <label for="attending-yes-<?php echo $index; ?>">Yes</label>
    </div>
    <div class="guest__options-group">
      <input class="guest__attendance-input" id="attending-no-<?php echo $index; ?>" type="radio" name="attending[<?php echo htmlspecialchars($clean_guest); ?>]" value="no" required/>
      <label for="attending-no-<?php echo $index; ?>">No</label>
    </div>
  </div>

  <?php }
  
} ?>

修改后,表单提交时$_POST['attending']会变成一个关联数组,键是宾客姓名,值是对应的选择(yes/no)。

第二步:处理POST提交的数据

遍历提交的数组,分别收集选择"Yes"和"No"的宾客姓名,再转换成逗号分隔的字符串适配数据库存储:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $attending_yes = [];
    $attending_no = [];

    // 遍历出席数据,分类收集姓名
    foreach ($_POST['attending'] as $guest_name => $status) {
        $clean_name = trim($guest_name);
        if ($status === 'yes') {
            $attending_yes[] = $clean_name;
        } elseif ($status === 'no') {
            $attending_no[] = $clean_name;
        }
    }

    // 转换成数据库需要的逗号分隔格式
    $yes_str = implode(', ', $attending_yes);
    $no_str = implode(', ', $attending_no);

    // 后续写入数据库时,请使用预处理语句防止SQL注入
    // 示例:
    // $stmt = $pdo->prepare("INSERT INTO 表名 (attending_yes, attending_no) VALUES (?, ?)");
    // $stmt->execute([$yes_str, $no_str]);
}
?>

注意事项

  • 用htmlspecialchars()处理姓名是为了避免特殊字符破坏HTML结构;
  • 写入数据库必须用预处理语句,禁止直接拼接SQL字符串;
  • 如果存在重名宾客,建议改用数据库中宾客的唯一ID作为数组键,同时通过隐藏字段传递ID与姓名的对应关系,保证数据准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 23:55:20