douju2012 2013-03-19 20:26
浏览 79
已采纳

PHP多选表单在MySQL中插入多行

I have the following code used to insert a record using PHP into a MySQL database. The form element is a multiple select that works fine when only one option is selected. When I choose more than 1 option, only the last option is inserted. How do I have the form create a new row for each option selected in the multiple select?

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "InsertForm")) {
  $insertSQL = sprintf("INSERT INTO emplikons (EmpNo, IconId) VALUES (%s, %s)",
                       GetSQLValueString($_POST['insertRecordID'], "text"),
                       GetSQLValueString($_POST['icons'], "int"));

  mysql_select_db($database_techsterus, $techsterus);
  $Result1 = mysql_query($insertSQL, $techsterus) or die(mysql_error());

This is the code of the form element. It uses a recordset to dynamically pull values from another table:

<select name="icons" size="10" multiple="multiple">
            <?php
do {  
?>
            <option value="<?php echo $row_icons['id']?>"><?php echo $row_icons['name']?></option>
            <?php
} while ($row_icons = mysql_fetch_assoc($icons));
  $rows = mysql_num_rows($icons);
  if($rows > 0) {
      mysql_data_seek($icons, 0);
      $row_icons = mysql_fetch_assoc($icons);
  }
?>
          </select>
  • 写回答

1条回答 默认 最新

  • dte49889 2013-03-19 20:56
    关注

    add [] to the name of the select, to get an array of all selected values.

    <select name="icons[]" size="10" multiple="multiple">
    

    Then, read from $_POST / $_GET... (assuming form method="post")

    $sql = '';
    foreach ($_POST['icons'] as $icon) {
    
        // no idea where to get EmpNo from, let's assume it is in $empno.
        $sql .= "('$empno','$icon'),";
    
    }
    
    $sql = "INSERT INTO tablename (EmpNo, IconId) VALUES " . trim($sql,',');
    
    // Now, please use mysqli_* or PDO instead of mysql_* 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用