【问题标题】:Substract Session[cart] QUANTITY to STOCK QUANTITY in db减去 Session[cart] QUANTITY 到 db 中的 STOCK QUANTITY
【发布时间】:2012-11-04 11:47:23
【问题描述】:

我有一个表格,其中显示了 ($_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']”中我还应该说将 QUANTITY UPDATED 减去 DATA BASE QUANTITY 但我不知道该怎么做。有帮助吗?

【问题讨论】:

标签: php


【解决方案1】:

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

希望它对你有用!

问候!

【讨论】:

    猜你喜欢
    • 2019-08-11
    • 1970-01-01
    • 2021-01-06
    • 2021-09-02
    • 2012-12-05
    • 2021-10-03
    • 2021-06-01
    • 2021-05-19
    • 2017-04-05
    相关资源
    最近更新 更多