簡體   English   中英

將多個復選框值添加到一行中的多個列

[英]Adding multiple checkbox values to multiple columns in a single row

我讀了其他線程,但不認為我已經找到答案了(或者也許只是不知道如何實現...)。 我有一個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

我以為正在創建的字符串是一系列復選框值,它們被分離出來以插入到各列中-這正是我想要發生的事情-但顯然它沒有用。 我顯然對數組不是很熟悉,因此如果這是一個簡單的問題,我深表歉意。

非常感謝任何人都可以提供的幫助...

substr()的第一個參數必須是字符串,您將為其提供一個數組,如您從var_dump語句的輸出中所見:

array(2) { [0]=> string(1) "2" [1]=> string(1) "4" }

正如BuseGönen的注釋所建議的,join函數使您可以將數組轉換為帶有逗號分隔值的字符串(在示例中提供的數組將為字符串“ 2,4”)。

$allsizes array no string 

$itemSizing = join(',',$allsizes); 

刪除代碼

$itemSizing="";
foreach($allsizes as $size){
    $itemSizing .=$size .",";
}
$itemSizing=substr($allsizes, 0, -2);

由於您的值是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 and Large示例為例,您的字符串將是-

NULL, 1, NULL, 1

2個錯別字

更改

$itemSizing=substr($allsizes, 0, -2);

$itemSizing=substr($itemSizing, 0, -1);//-1 to remove trailing ,

也改變

$decsription=$_POST["description"];

$description=$_POST["description"];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM