簡體   English   中英

將會話[購物車]減去數量以db中的庫存數量

[英]Substract Session[cart] QUANTITY to STOCK QUANTITY in db

我有一張桌子,上面顯示着($ _SESSION ['cart']產品,里面有一個表格,可以在其中手動輸入想要的數量到($ _SESSION ['cart']產品中。

    <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'])的那些數量替換數據庫中STOCK中的數量。

我認為在最后的“ foreach($ _POST ['qty']”中,我也應該說將UPDATE QUANTITY減去數據庫QUANTITY,但是我不知道該怎么做。有什么幫助嗎?

1)將value =\\"{$_SESSION['cart'][$product_id]}\\"替換為value =\\"{$quantity}\\" 您已經在foreach語句中對其進行了檢索。 2)對於數據庫,如果您使用的是mysql,我建議您使用PDO訪問數據庫(由於缺少縮進和不匹配的括號,我重寫了第二段代碼):

<?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));
      }
   }
}
?>

希望這對你有用!

問候!

暫無
暫無

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

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