0

我试图只从名为“Addbox”的复选框为真的行中添加值,下面的代码识别复选框何时被勾选,并且只将这些项目添加到用户的愿望清单中。但是,无论复选框是真还是假,它都会将它们与前一行的数量相加。

复选框代码是

"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)
}
4

1 回答 1

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以及项目的$itemId, 或值(您创建了项目 ID)。然后它将附加到您的 SQL 字符串。

警告:您通常希望通过健全性和有效性检查来防止恶意客户端。StackOverflow 上已经有一些很好的答案来防止 SQL 注入。您还需要检查空的、无效的字符、溢出的数字等。这个片段现在很容易受到攻击,如果$key$itemId包含意外的值(包括未设置或为空),可能会导致问题。

更多信息foreach()http ://us2.php.net/manual/en/control-structures.foreach.php

于 2013-05-23T19:59:29.800 回答