2012-11-15 18 views
0

我有一個表,它顯示($ _SESSION ['cart']與一個窗體裏面,我可以手動引入我想要的數量到我的($ _SESSION [ '購物車']產品。Substract Session [cart]數量到股票數量在db

<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 [ '購物車'])數量

<?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 [‘數量’]」我也要說。減去更新到數據庫數量QUANTITY但我不知道該怎麼做。任何幫助嗎?

+0

http://en.wikipedia.org/wiki/SQL_Update –

回答

0

1)將value =\"{$_SESSION['cart'][$product_id]}\"替換爲value =\"{$quantity}\"。您已經在foreach聲明中檢索到它。 2)對於數據庫,有你使用MySQL的,我會reccommend訪問與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)); 
     } 
    } 
} 
?> 

希望它適合你!

問候!

+0

非常感謝它完美地工作。 – user1757383