将多个复选框值添加到单个行中的多个列

i read other threads but don't think i have found the answer (or maybe just don't know how to implement it...) for this. i have a mysql table with columns for an item size, amongst other things. the user fills in a form in which mulitple sizes may be selected from a series of checkboxes. i want to be able to insert the selected checkbox values in to the proper columns while leaving the other columns either null or if necessary i guess as a 0 value. the columns are tinyint format right now.

'One Size'

<input type="checkbox" name="itemSize[]" value="1" />

Small

<input type="checkbox" name="itemSize[]" value="2" />

Medium

<input type="checkbox" name="itemSize[]" value="3" />

Large

<input type="checkbox" name="itemSize[]" value="4" />

the database table has columns named oneSize, small, medium and large.


HERE IS THE CODE I USED TO TRY TO INSERT A RECORD BASED ON AN ARTICLE IN FOUND IN THE FORUM:

$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"];

and then in the insert statement i tried listing each column and then the values for the 4 item sizes taken from the checkboxes are listed as the concatenated string:

$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')";

THIS IS THE ERROR MESSAGE I GOT WHEN ATTEMPTING TO INSERT A RECORD FEATURING A SMALL SIZE AND A LARGE SIZE CHECKED OFF AND THE OTHER TWO CHECKBOXES LEFT UNCHECKED:

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

I thought that the string being created was a series of the checkbox values separated out for insertion into the various columns - which is exactly what I want to happen - but clearly it didn't work. I am obviously not very familiar with arrays so I apologize if this is a simple question.

thanks very much for any help anyone can provide...

查看全部
dream518518518
dream518518518
2014/12/29 20:31
  • checkbox
  • php
  • mysql
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

4个回复