0

($ _SESSION [' cart '] PRODUCTS.

    <form name="formulario2" method="POST" target="oculto"><input type="hidden" name="action" value="update">
    foreach($_SESSION['cart'] as $product_id => $quantity) { 
    echo "<td align=\"center\"><input type = \"text\" size=\"1\" name=\"qty[$product_id]\" value =\"{$_SESSION['cart'][$product_id]}\"></td>";
}
</form>

次に、以下を使用して ($_SESSION['cart']) 数量を更新します

    <?php
    if(isset($_POST['action']) && ($_POST['action'] =='update')){
    //
    foreach ($_POST['qty'] as $product_id=> $quantity){
    $qty = (int)$quantity;
    if ($qty > 0){
    $_SESSION['cart'][$product_id] = $qty;
    }
    }
    }
    ?>

ここで、($_SESSION['cart']) に UPDATED した数量をデータベースの STOCK の数量に減算したいと思います

最後の "foreach ($_POST['qty']" では、更新された数量をデータベース数量から差し引く必要があると思いますが、その方法がわかりません。

4

1 に答える 1

0

1)に置き換えvalue =\"{$_SESSION['cart'][$product_id]}\"ますvalue =\"{$quantity}\"foreachステートメントですでに取得されています。2)データベースの場合、mysqlを使用する場合は、PDOを使用してデータベースにアクセスすることをお勧めします(インデントがなく、括弧が一致しないため、2番目のコードブロックを書き直しました)。

<?php
  if ((isset($_POST['action']) && ($_POST['action'] == 'update'))
  {
    foreach ($_POST['qty'] as $product_id => $quantity)
    {
      $qty = intval($quantity);
      $pid = intval($product_id); // ALSO use the intval of the $product_id,
                                  // since it was in a form and it can be hacked
      $_SESSION['cart'][$pid] = $qty; // NOTE: you need to also update the
                                      // session`s cart with 0 values, or
                                      // at least to unset the respective
                                      // product:
                                      // unset($_SESSION['cart'][$pid])
      if ($qty > 0)
      {
        // now update the DB:
        $mysql_host = "127.0.0.1";
        $mysql_user = "root";
        $mysql_password = "";
        $mysql_database = "myShop";
        $dbLink = new PDO("mysql:host=$mysql_host;dbname=$mysql_database;charset=utf8", $mysql_user, $mysql_password, array(PDO::ATTR_PERSISTENT => true));
        $dbLink->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
        $query = $dbLink->prepare("update `products` set `stock` = `stock` - ? WHERE `productId` = ? limit 1");
        $query->execute(array($qty, $pid));
      }
   }
}
?>

それがあなたのために働くことを願っています!

よろしく!

于 2012-11-15T19:59:03.720 に答える