在db中将Session [cart] QUANTITY减去STOCK QUANTITY

时间:2012-11-15 19:44:34

标签: php

我有一张表格显示($ _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;
    }
    }
    }
    ?>

现在我想 SUBSTRACT 我已经更新到($ _SESSION ['cart'])的数量到我的数据库中的STOCK数量。

我认为在最后一个“foreach($ _POST ['qty']”中我还应该说将QUANTITY UPDATED减去数据基础量,但我不知道该怎么做。任何帮助?

1 个答案:

答案 0 :(得分:0)

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

希望它适合你!

问候!