2013-03-19 53 views
0

插入多行我有用來插入使用PHP到MySQL數據庫中的記錄下面的代碼。當只有一個選項被選中時,表單元素是一個多選選項,可以正常工作。當我選擇多個選項時,只會插入最後一個選項。如何讓表單爲多重選擇中的每個選項創建一個新行?PHP多選的形式在MySQL

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()); 

這是表單元素的代碼。它使用一個記錄到另一個表中動態獲取值:

<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> 
+0

您可以添加形式的代碼,特別是多選輸入? – thaJeztah 2013-03-19 20:29:19

+2

[**在新的代碼,請不要使用'mysql_ *'功能**](http://bit.ly/phpmsql)。他們不再被維護[並且被正式棄用](http://j.mp/XqV7Lp)。看到[**紅框**](http://j.mp/Te9zIL)?學習[*準備的語句*](http://j.mp/T9hLWi),並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [這篇文章](http://j.mp/QEx8IB)將幫助你決定哪個。如果你選擇PDO,[這裏是一個很好的教程](http://j.mp/PoWehJ)。 – 2013-03-19 20:29:47

+0

@thaJeztah,問題現在更新。謝謝。對於信息 – 2013-03-19 20:45:53

回答

3

添加[]到選擇的名字,讓所有選擇值的數組。

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

然後,從$_POST/$_GET讀...(假設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_* 
+0

但是,你也必須更新插入查詢,因爲當前查詢只是將單行 – thaJeztah 2013-03-19 20:59:56

+0

@michi EMPNO是一個會話變量,但我得到一個500服務器錯誤,當我插入這樣的:$ row_WADAsess [ 'EMPNO'] 是不是因爲 'EMPNO' 的?我如何逃避? – 2013-03-19 21:28:35

+1

@RoccoTheTaco:$ _SESSION ['nameofvariable']? – michi 2013-03-19 21:51:14