我阅读了其他线程,但我认为我没有找到答案(或者可能只是不知道如何实现它...... 我有一个 MySQL 表,其中包含项目大小的列等。 用户填写一个表单,其中可以从一系列复选框中选择多种大小。 我希望能够将选定的复选框值插入到正确的列中,同时将其他列保留为 null 或在必要时我猜为 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"];
然后在 insert 语句中,我尝试列出每一列,然后从复选框中获取的 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
$allsizes array no string
例
$itemSizing = join(',',$allsizes);
删除代码
$itemSizing="";
foreach($allsizes as $size){
$itemSizing .=$size .",";
}
$itemSizing=substr($allsizes, 0, -2);
2 拼写错误
改变
$itemSizing=substr($allsizes, 0, -2);
自
$itemSizing=substr($itemSizing, 0, -1);//-1 to remove trailing ,
也改变
$decsription=$_POST["description"];
自
$description=$_POST["description"];
substr() 的第一个参数必须是字符串,你为它提供一个数组,从 var_dump 语句的输出中可以看出:
array(2) { [0]=> string(1) "2" [1]=> string(1) "4" }
正如 Buse Gönen 的评论所建议的那样,join 函数使您能够将数组转换为带有逗号分隔值的字符串(您在示例中提供的数组将是字符串"2,4")。