0

「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)
}
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 文字列に追加されます。

警告:通常、健全性と有効性のチェックを使用して、悪意のあるクライアントを防止する必要があります。SQL インジェクションを防止するための適切な回答が StackOverflow に既にいくつかあります。また、空の文字、無効な文字、数値のオーバーフローなども確認する必要があります。このスニペットは現在のところ脆弱であり、意図しない値 (設定されていない、空であるなど) が含まれている$key場合に問題が発生する可能性があります。$itemId

詳細情報foreach(): http://us2.php.net/manual/en/control-structures.foreach.php

于 2013-05-23T19:59:29.800 に答える