繁体   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