减少MySQL购物车中的商品数量

时间:2017-05-08 17:33:21

标签: php html mysql database

我正在忙着创建一个购物车php项目,我已成功完成添加,删除和更新项目到购物车,但我坚持的部分是用户点击"继续结帐"按钮我希望购物车中的任何内容在数据库中相应减少。例如,如果一个人在他的购物车中: 2 x产品之一 3 x产品二

如果销售完成,我希望减少我手头的金额。请有人帮忙 这是我的购物车代码:

<?php
session_start();
@mysql_connect("localhost","root","") or die("Could not connect to database");
@mysql_select_db("bookstore") or die("Could not select database");
include("admin/php/myFunctions.php");

if(!empty($_GET['prodid'])){
    $pid = $_GET['prodid'];
    $wasFound = false;
    $i = 0;
    if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
        $_SESSION["cart_array"]=array(0=>array("productID"=>$pid,"quantity"=>1));
    }else{
        foreach($_SESSION["cart_array"] as $each_product){
            $i++;
            while(list($key,$value)=each($each_product)){
                if($key=="productID" && $value==$pid){  
                    array_splice($_SESSION["cart_array"],$i-1,1,array(array("productID"=>$pid,"quantity"=>$each_product ['quantity']+1)));
                    $wasFound=true;
                }
            }       
        }
        if($wasFound==false){
            array_push($_SESSION["cart_array"],array("productID"=>$pid,"quantity"=>1));
        }
    }
    header("location:shoppingcart.php");
    exit();
}
//-------------------------------------------------------------------------------------------------
$submit = $_POST['btnUpdate'];
if($submit == "Update"){
    $x = 0;

    foreach($_SESSION["cart_array"] as $each_product){
        @$i++;
        $quantity = $_POST['txtQuan'.$x];
        $prodStock = $_POST['txtHoldQuan'.$x];
        $prodAdjustId = $_POST['txtHoldProdId'.$x++];
        if($quantity<1){ $quantity = 1; }
        if($quantity>$prodStock){ $quantity = $prodStock; }
        while(list($key,$value)=each($each_product)){
            array_splice($_SESSION["cart_array"],$i-1,1,array(array("productID"=>$prodAdjustId,"quantity"=>$quantity)));
        }       
    }


}
//-------------------------------------------------------------------------------------------------
if(!empty($_GET['cid']) || isset($_GET['cid'])){
    $removeKey = $_GET['cid'];
    if(count($_SESSION["cart_array"])<=1){
        unset($_SESSION["cart_array"]);
    }else{
        unset($_SESSION["cart_array"]["$removeKey"]);
        sort($_SESSION["cart_array"]);
    }
}
//-------------------------------------------------------------------------------------------------
$cartTitle = "";
$cartOutput = "";
$cartTotal = "";
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
    $cartOutput="<h2 align='center'> Your shopping cart is empty </h2>";
}else{
    $x = 0;
    $cartTitle .= '<form name="shoppingcart_form" action="shoppingcart.php" method="post" /><table width="700px" cellspacing="0" cellpadding="5">
            <tr bgcolor="#CCCCCC">
                        <th width="220" align="left">Image </th> 
                        <th width="140" align="left">Name </th> 
                        <th width="100" align="center">Quantity </th> 
                        <th width="60" align="center">Stock </th> 
                        <th width="60" align="right">Price </th> 
                        <th width="60" align="right">Total </th> 
                        <th width="90"> </th></tr>';
    $i = 0;
    foreach($_SESSION["cart_array"] as $each_product){
        $product_id = $each_product['productID'];
        $sql=mysql_query("select * from tblproduct where prod_id='$product_id' limit 1");
        while($row=mysql_fetch_array($sql)){
            $prodNo = $row["prod_no"];
            $prodID = $row["prod_id"];
            $prodName = $row["prod_name"];
            $prodPrice = $row["prod_price"];
            $prodQuan = $row["prod_quan"];
        }
        $pricetotal=$prodPrice*$each_product['quantity'];
        $cartTotal= number_format($pricetotal+$cartTotal,2);
        $cartOutput .= '<tr><td><img style="border: 2px solid;" src="images/product/'.$prodNo.'.jpg" width="150" height="120" /></td> 
            <td>'.$prodName.'</td> 
            <td align="center"><input type="hidden" name="txtHoldProdId'.$i.'" value="'.$prodID.'" /><input name="txtQuan'.$i.'" type="text" value="'.$each_product['quantity'].'" style="width: 40px; text-align: center" /> </td>
            <td align="center"><input type="hidden" name="txtHoldQuan'.$i.'" value="'.$prodQuan.'" /> '.$prodQuan   .' pcs</td> 
            <td align="right">R '.$prodPrice.'</td> 
            <td align="right">R '.$pricetotal.'</td>
            <td align="center"> <a href="shoppingcart.php?cid='.$i++.'"><img src="images/remove_x.gif" alt="remove" /><br />Remove</a> </td></tr>';
    }
    $_SESSION['checkoutCartTotal'] = $cartTotal;
    $cartOutput .= '<tr>
                        <td colspan="3" align="right"  height="40px">Have you modified your basket? Please click here to <input class="btn_upd" type="submit" name="btnUpdate" value="Update" />&nbsp;&nbsp;</td>
                        <td align="right" style="background:#ccc; font-weight:bold"> Total: </td>
                        <td colspan="2" align="left" style="background:#ccc; font-weight:bold;">R '.$cartTotal.' </td>
                        <td style="background:#ccc; font-weight:bold"> </td>
                    </tr>
                </table>
                <div style="float:right; width: 215px; margin-top: 20px;">

                    <div class="checkout"><a href="checkout.php" class="more">Proceed to Checkout</a></div>

                </div></form>';
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Great Selling Book Store</title>
<link href="css/slider.css" rel="stylesheet" type="text/css" />

<link rel="stylesheet" type="text/css" href="css/ddsmoothmenu.css" />

<link rel="stylesheet" type="text/css" href="css/styles.css" />

<script language="javascript" type="text/javascript">

    function clearText(field)
    {
        if (field.defaultValue == field.value) field.value = '';
        else if (field.value == '') field.value = field.defaultValue;
    }
</script>

</head>

<body id="subpage">

<div id="main_wrapper">
    <div id="main_header">
        <div id="site_title"><h1><a href="#" rel="nofollow">Great Selling book Store</a></h1></div>

        <div id="header_right">
            <div id="main_search">
                <form action="products.php" method="get" name="search_form">
                  <input type="text" value="Search" name="keyword" onfocus="clearText(this)" onblur="clearText(this)" class="txt_field" />
                  <input type="submit" name="Search" value="" alt="Search" id="searchbutton" title="Search" class="sub_btn"  />
                </form>
            </div>
         </div> <!-- END -->
    </div> <!-- END of header -->

    <div id="main_menu" class="ddsmoothmenu">
        <ul>
            <li><a href="index.php">Home</a></li>
            <li><a href="products.php">Books</a></li>
            <li><a class="selected" href="shoppingcart.php">Cart</a></li>
            <li><a href="checkout.php">Checkout</a></li>
            <li><a href="about.php">About</a></li>
        </ul>
        <br style="clear: left" />
    </div> <!-- end of menu -->

    <div class="cleaner h20"></div>
    <div id="main_top"></div>
    <div id="main">

        <div id="sidebar">
            <h3>Categories</h3>
            <ul class="sidebar_menu">
                <li><a href="index.php?cat=children">Children</a></li>              
                <li><a href="index.php?cat=Horror">Horror</a></li>
                <li><a href="index.php?cat=Thriller">Thriller</a></li>
        </ul>
        </div> <!-- END of sidebar -->

        <div id="content">
        <?php echo $cartTitle; ?>
        <?php echo $cartOutput; ?>

        </div> <!-- end of content -->
        <div class="cleaner"></div>
    </div> <!-- END of main -->

    <div id="main_footer">   
        <div class="cleaner h40"></div>
        <center>
            Copyright © 2048 DigitalNinja
        </center>
    </div> <!-- END of footer -->   

</div>


<script type='text/javascript' src='js/logging.js'></script>
</body>
</html>

这是我在我的数据库中使用的表格:

    CREATE TABLE IF NOT EXISTS `tblproduct` (
  `prod_no` int(10) NOT NULL AUTO_INCREMENT,
  `prod_id` int(15) NOT NULL,
  `prod_name` varchar(100) NOT NULL,
  `prod_descr` text NOT NULL,
  `prod_cat` varchar(100) NOT NULL,
  `prod_price` float NOT NULL,
  `prod_quan` int(10) NOT NULL,
  `date_added` datetime NOT NULL,
  `ISBN` varchar(100) NOT NULL,
  PRIMARY KEY (`prod_no`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;



INSERT INTO `tblproduct` (`prod_no`, `prod_id`, `prod_name`, `prod_descr`, `prod_cat`, `prod_price`, `prod_quan`, `date_added`, `ISBN`) VALUES
(1, 1, 'Charlie and the chocolate factory', 'prod description', 'Children', 80, 100, '2016-11-01 08:25:36', '9785811243570'),
(2, 2, 'Frankenstein', 'Prod description', 'Horror', 120, 80, '2017-05-01 05:27:11', '9781608438037'),
(3, 3, 'The Girl on the Train', 'Prod Description', 'Thriller', 200, 90, '2017-01-18 04:22:22', '9784062932530');

3 个答案:

答案 0 :(得分:1)

与mysql update books set TotalBooks = TotalBooks-1 where Id = ?正常工作

答案 1 :(得分:0)

买方下订单后,您需要在数据库中输入一个条目:

UPDATE `tblproduct` SET prod_quan=prod_quan-$order_count WHERE prod_id=$product_id;

其中$ order_count是订购数量,$ product_id - 订购产品。对每个订购的产品进行此更新。

答案 2 :(得分:0)

假设订单存储在另一个表中,并保留对产品的引用,您应该能够执行以下操作:

set.seed(1121)
gen_state <- function() {
  days <- 100
  CURstate <- 1
  state <- numeric(days)
  for (i in 1:days) {
    randomNum <- runif(1)
    if (CURstate == 0) {
      if (randomNum < .04) {
        CURstate <- 1
      } else{
        CURstate <- 0
      }
    } else{
      if (randomNum < .11) {
        CURstate <- 0
      } else{
        CURstate <- 1
      }
    }
    state[i] <- CURstate
  }
  return(state)
}

state_matrix <- t(replicate(1000,gen_state()))

注意:如果产品可以多次以相同的顺序出现,则可能会出现一些问题。