Php 将会话[cart]数量减去数据库中的库存数量
我有一个表格,其中显示了($_SESSION['cart']),里面有一个表格,我可以手动将所需数量导入($_SESSION['cart']产品中Php 将会话[cart]数量减去数据库中的库存数量,php,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 => $qu
<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>
foreach($_SESSION['cart']作为$product_id=>$quantity){
回声“;
}
然后,我使用以下命令更新($_SESSION['cart'])数量
现在我想将我更新到($_SESSION['cart'])的数量减去我数据库中的库存数量
我认为在最后一个“foreach($\u POST['qty']”中,我还应该说将更新的数量减去数据库数量,但我不知道如何做。有什么帮助吗?1)替换value=\“{$\u SESSION['cart'][$product\u id]}\”
为value=\“{$QUANTITY}”
。您已经在foreach
语句中检索到了它。
2) 对于数据库,如果您使用mysql,我建议您使用PDO访问数据库(由于缺少缩进和括号不匹配,我已经重写了您的第二段代码):
<?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;
}
}
}
?>
<?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));
}
}
}
?>