我阅读了其他线程,但认为我没有找到答案(或者可能只是不知道如何实现它......)。我有一个 mysql 表,其中包含项目大小等列。用户填写一个表格,可以从一系列复选框中选择多种尺寸。我希望能够将选定的复选框值插入到正确的列中,同时将其他列保留为空,或者如果需要,我猜为 0 值。这些列现在是tinyint 格式。
“单一尺寸”
<input type="checkbox" name="itemSize[]" value="1" />
小
<input type="checkbox" name="itemSize[]" value="2" />
中
<input type="checkbox" name="itemSize[]" value="3" />
大
<input type="checkbox" name="itemSize[]" value="4" />
数据库表包含名为 oneSize、小、中和大的列。
<小时/>这是我用来尝试根据论坛中找到的文章插入记录的代码:
$itemName=$_POST["itemName"];
$allsizes=$_POST["itemSize"];
var_dump($allsizes);
$itemSizing="";
foreach($allsizes as $size){
$itemSizing .=$size .",";
}
$itemSizing=substr($allsizes, 0, -2);
$price=$_POST["price"];
$smallPrice=$_POST["smallPrice"];
$mediumPrice=$_POST["mediumPrice"];
$largePrice=$_POST["largePrice"];
$decsription=$_POST["description"];
$category_id=$_POST["category_id"];
然后在插入语句中我尝试列出每一列,然后将从复选框中获取的 4 个项目大小的值列为连接字符串:
$SQL="INSERT INTO menuItems (itemName,oneSize,small,medium, large,price,smallPrice,mediumPrice,largePrice,description,category_id) VALUES ('$itemName','$itemSizing','$price','$smallPrice','$mediumPrice','$largePrice','$description','$category_id')";
这是我在尝试插入小尺寸和大尺寸的记录时收到的错误消息,该记录已选中,而其他两个复选框未选中:
array(2) { [0]=> string(1) "2" [1]=> string(1) "4" }
Warning: substr() expects parameter 1 to be string, array given in menuItems.php on line 162
INSERT INTO menuItems (itemName,oneSize,small,medium,large,price,smallPrice,mediumPrice,largePrice,description,category_id) VALUES ('Garden Salad','','','3.99','','6.99','Fresh greens with lettuce, tomatoes and cucumbers. Served with your choice of dressing.','3') : Error in query. Contact Site Admin
<小时/>
我认为正在创建的字符串是一系列分离出来的复选框值,用于插入到各个列中 - 这正是我想要发生的 - 但显然它不起作用。我显然对数组不是很熟悉,所以如果这是一个简单的问题,我很抱歉。
非常感谢任何人可以提供的任何帮助...
最佳答案
由于您的值是 1-4
,您可以使用 for 循环来检查每个值是否在 POST
数组中,然后创建您的 $itemSizing
字符串 -
//a size array
$itemSizingArray = array();
//for loop for each size value
for($i=1;$i<=4;$i++){
//add either a '1' or 'NULL' to the array, based on if the checkbox value is in the array
$itemSizingArray[] = (in_array($i,$_POST["itemSize"]) ? 1: 'NULL');
}
//implode the array
$itemSizing = implode(', ',$itemSizingArray);
因此,通过您的 Small
和 Large
示例检查您的字符串将是 -
NULL, 1, NULL, 1
关于php - 将多个复选框值添加到单行中的多个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27695582/