0

我有一个表格,其中显示 ($_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']”中,我还应该说将更新的数量减去数据库数量,但我不知道该怎么做。有帮助吗?

4

1 回答 1

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

希望对你有帮助!

问候!

于 2012-11-15T19:59:03.720 回答