我尝试仅添加名为“Addbox”的复选框为true的行中的值,下面的代码标识何时勾选复选框并仅将这些项添加到用户心愿单。但是,无论复选框是true还是false,它都会将它们与前一行的数量相加。
复选框代码是
"input type = 'checkbox' name='Addbox[]' value='" . $row['Item_ID'] . "'
如果声明代码是
if (isset($_POST['Add'])) {
if(isset ($_POST['Addbox'])){
//counts the size of the array addbox[] so the for loop has an end.
$count = count($_POST['Addbox']);
//starts the sql query string to added to inside the for loop.
$sql = "INSERT INTO `wishlist` (`User_ID`,`Product_ID`,`Quantity`) VALUES ";
//initiate for loop... do this until every row in the array has been looked at essentially.
for ($i=0; $i < $count; $i++) {
//get the values of this row.
$item = $_POST['Addbox'][$i];
$quantity = $_POST['quantity'][$i];
// Add the end of the sql string for each of the loops.
$sql .= "($userid, $item, $quantity)";
//This check is it is the last of the row in the array. If it isnt add a comma and space ready for the next row.
if($i !== $count-1){
$sql .= ", ";
}
}
mysql_query($sql);
// var_dump($sql)
}
答案 0 :(得分:0)
试试这个:
foreach($_POST['Addbox'] as $key=>$itemId){
//get the values of this row.
$item = $_POST['Addbox'][$key];
$quantity = if (!empty($_POST['quantity'][$key])) $_POST['quantity'][$key]; else 0;
// Could also be written as $quantity = !empty($_POST['quantity'][$key]) ? $_POST['quantity'][$key] : 0;
// Add the end of the sql string for each of the loops.
$sql .= "($userid, $item, $quantity)";
}
对于HTML,请尝试以下方法:
"<input type='checkbox' name='Addbox[{$row['Item_ID']}]' value='{$row['Item_ID']}' />"
这将迭代数组$_POST['Addbox']
中的每个项目,并在数组和项目的$key
或值(您创建项目ID)中为其提供$itemId
。然后它将附加到您的SQL字符串。
警告:您通常希望通过完整性和有效性检查来防止恶意客户端。 StackOverflow上已有一些很好的答案可以防止SQL注入。您还需要检查空的,无效的字符,溢出的数字等。此片段现在很容易受到攻击,如果$key
或$itemId
包含非预期的值(包括未设置或空)。
有关foreach()
的更多信息:http://us2.php.net/manual/en/control-structures.foreach.php