我不知道如何构建PHP/MySQL查询来实现这一点。我正在尝试添加项目到一个列表。我有一个表单,其中列出了多个复选框表单的所有项目。对于选中的每个项目,我需要它在MYSQL表中创建一个新条目。该表有三个字段:entry_id、list_id和item_id。
那么,如果我显示一个包含5个项目的列表
列表# 1
- 第1项
- 项3
- 第四项
- 第五项
选中3
列表# 1
- 第1项
- 项2 *
- 项3 *
- 第四项
- 第五项*
我需要php/mysql代码将这些值插入到表中,如下所示:
- entry_id/list_id/item_id
- 1/1/2
- 2/1/3
- 3/1/5
明白了吗?
应该这样做:
<?php
// get array of selected elements
$selections = $_POST['selections'];
$list = intval($_POST['list_id'], 10);
// prevent sql injection
$selections = array_map(function ($el) {
return intval($el, 10);
}, $selections);
// create tuples
$selections = array_map(function ($el) use ($list) {
return '(' . $list . ', ' . $el . ')';
}, $selections);
// create a comma sperated list of tuples
$selections = implode(', ', $selections);
$sql = 'INSERT INTO table (list_id, item_id) VALUES ' . $selections . ';';
// run $sql through the driver of your choice
?>
使用如下HTML:
<strong>List Number 1</strong>
<ul>
<li><label><input type="checkbox" name="checked[1][]" value="1">Value 1</label></li>
<li><label><input type="checkbox" name="checked[1][]" value="2">Value 2</label></li>
<li><label><input type="checkbox" name="checked[1][]" value="3">Value 3</label></li>
<li><label><input type="checkbox" name="checked[1][]" value="4">Value 4</label></li>
<li><label><input type="checkbox" name="checked[1][]" value="5">Value 5</label></li>
</ul>
<strong>List Number 2</strong>
<ul>
<li><label><input type="checkbox" name="checked[2][]" value="1">Value 1</label></li>
<li><label><input type="checkbox" name="checked[2][]" value="2">Value 2</label></li>
<li><label><input type="checkbox" name="checked[2][]" value="3">Value 3</label></li>
<li><label><input type="checkbox" name="checked[2][]" value="4">Value 4</label></li>
<li><label><input type="checkbox" name="checked[2][]" value="5">Value 5</label></li>
</ul>
其中name
参数的格式为checked[X][]
,其中"X"为List ID。
在提交时,使用您问题中提到的值,您将得到:
array(1) {
[1]=>
array(3) {
[0]=>
string(1) "2"
[1]=>
string(1) "3"
[2]=>
string(1) "5"
}
}
要生成一个像OP中提到的那样的数组:
$sqlValues = array();
foreach( $_POST['checked'] as $list_id => $values ){
foreach( $values as $k => $v ){
$sqlValues[] = ( $k+1 ).' , '.(int) $list_id.' , ' .(int) $v;
}
}
$sqlCmd = 'INSERT INTO `yourTable` ( `entry_id` , `list_id` , `item_id` )
VALUES ( '.implode( ' ) , ( ' , $sqlValues ).' )';