PHP多重选择表单可在MySQL中插入多行 [英] PHP multiple select form to insert multiple rows in MySQL
问题描述
我有以下代码,用于使用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());
这是form元素的代码.它使用一个记录集从另一个表中动态提取值:
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>
推荐答案
在选择的名称中添加[]
,以获取所有选择的值的数组.
add []
to the name of the select, to get an array of all selected values.
<select name="icons[]" size="10" multiple="multiple">
然后,从$_POST / $_GET
...(假设form method="post"
)中读取
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_*
这篇关于PHP多重选择表单可在MySQL中插入多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!