会话

时间:2018-05-08 08:49:37

标签: javascript php jquery html session

我正在使用我的兄弟帐户,因为我的帐户因某些问题而无法使用。

我正在开发一个电子商务网站。我的担忧与数量有关。

我有三个页面Test1.phpTest2.phpTest3.php以及一个名为ajax_cart.php的AJAX页面。并且它使用SESSION处理添加到购物车。

让我们来谈谈Test1.php页面 到目前为止,我在数据库中只有4个产品,我只显示数量用于测试目的。我的数量将从1开始。用户可以使用加号(+)和减号( - )来增加数量或减少数量。

enter image description here

现在我做了什么我将产品的数量从1增加到4,然后点击添加到购物车按钮。它在Top中显示正确的数量,例如" 4 view cart"。

enter image description here

Test1.php页面没有问题。我点击了view cart,然后点击Test2.php上的页面重定向。

让我们谈谈Test2.php页面

在此页面中,我只显示quantityproceed to check out。它只是为了测试。我在这个页面上得到了正确的数量。

enter image description here

现在我做了什么,我将Test2.php页面中的数量从4增加到6(任何东西) enter image description here

然后点击Proceed to checkout,然后该页面将重定向到Test3.php页面,但我的数量仅显示4。为什么4?因为SESSION但我的新数量是6。

所以我的问题是,我增加Test2.php中的数量,但由于Test3.php,我的数量未反映在SESSION页面中。

我正在分享谷歌驱动器链接,因为我无法在此处上传我的代码,因为它非常庞大。

https://drive.google.com/file/d/1KfJbjXlzwVIIX6IW9UKQYWHNKJ84P-3G/view?usp=sharing

你能在这个问题上帮助我吗?

ajax_cart.php

<?php
session_start();
include('connection.php');
 $action = $_POST['action'];
 $p_id   = $_POST['p_id'];

if (isset($_POST['quantity'])) {
         echo $quantity = $_POST['quantity'];
}

if($action == 'add'){
     if(!empty($p_id)){
           $query = "SELECT p_id, p_images, p_name, p_brandname, p_company, p_packing, p_oldprice, p_currentprice FROM products WHERE p_id=?";
            if ($stmt = $conn->prepare($query)) {
                $stmt->bind_param("i", $p_id);
                $stmt->execute();
                $stmt->bind_result($p_id,$p_images, $name, $brandname, $company, $packing, $oldprice, $currentprice);
                $stmt->fetch();
              }
             $product = array(
                "p_id"=>$p_id,
                "p_brandname"=>$brandname,
                "p_currentprice"=>$currentprice,
                "p_total"=>$currentprice*$quantity,
                "p_images"=>$p_images,
                "quantity"=>$quantity
             );
            // print_r($product);
        if(isset($_SESSION['product_cart']) && !empty($_SESSION['product_cart']))
        {
            if(!array_key_exists($p_id,$_SESSION['product_cart']))
            {
                $_SESSION['product_cart'][$p_id] = $product;
            }
            else{

                     $_SESSION['product_cart'][$p_id]['p_total'] += ($currentprice*$quantity);
                     $_SESSION['product_cart'][$p_id]['quantity'] += $quantity;
            }       
        }
        else{
          $_SESSION['product_cart'][$p_id] = $product;
        }
    }   
}
?>
<a class="text-center" href="test2.php">View Cart</a>

Test2.php

<?php 
session_start();
include('connection.php');
 ?>

<!doctype html>
<html lang="en">
<head>    
      <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

                <!-- table section ends here -->

                    <?php if(!empty($_SESSION['product_cart'])){?>
                    <form action="test3.php" method="post">
                    <?php  foreach($_SESSION['product_cart'] as $key=>$product):?>
                      <div class="product-snipet">
                                <div class="sp-quantity">
                                    <div class="sp-minus fff"><a class="eee" href="javascript:void(0)" data-multi="-1">-</a></div>
                                    <div class="sp-input">
                                        <input type="text" class="quntity-input" value="<?php echo $product['quantity'];?>" />
                                    </div>
                                    <div class="sp-plus fff"><a class="eee" href="javascript:void(0)" data-multi="1">+</a></div>
                                </div>
                              </div>
                            <?php endforeach;?>
                            <input type="submit" name="submit" class="active" value="Proceed to checkout">
                     </form>
                    <?php }else{echo "<h2 style='font-size:22px'>Cart is empty</h2>";}
                    ?>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script type="text/javascript">
        /*increase the product qty*/
  updateTotal();
$('a.eee').click(function() {

  var $productContainer = $(this).closest('div.sp-quantity');
  var $pro_list = $(this).closest('tr.pro-list');
  var productPrice = parseFloat($pro_list.find('span.price_cal').text());
  var $quantityInput = $productContainer.find('input.quntity-input');
  var newQuantity = parseFloat($quantityInput.val()) + parseFloat($(this).data('multi'));

  if (newQuantity >= 1) {
    // Refresh quantity input.
    $quantityInput.val(newQuantity);

    // Refresh total div.
    var lineTotal = productPrice * newQuantity;
    $pro_list.find('td.total_amount').html('&#36;' + lineTotal);
    $pro_list.find('td.total_amount').data('price', lineTotal); //update data-price
  }
  updateTotal();
});

function updateTotal() {
  var subTotal = 0;
  var currencySymbol = "$";
  //start getting the total amounts from each product row.
  //add them as a subtotal.
  $("tr.pro-list > td.total_amount").each(function(index, element) {
    subTotal += parseFloat($(element).data("price")); //more secure to use data!
  });

  var total = subTotal + $("tr.pro-list.ship > td[data-price]").data("price");
  $("tr.pro-list.sub > td.subtotal").html(currencySymbol + "" + subTotal);
  $("tr.pro-list.total > td.total").html(currencySymbol + "" + total);
}

    </script>
</body>
</html>

Test3.php

 <?php 
     if(!empty($_SESSION['product_cart'])): foreach($_SESSION['product_cart'] as $key=>$product): ?>
       <b class="circle-qty"><?php echo $product['quantity'];?></b>
       <input type="hidden" name="o_product_qty[]" value="<?php echo $product['quantity'];?>"> 
       <?php endforeach;?>
       <?php endif;?> 

3 个答案:

答案 0 :(得分:1)

这是因为您没有在会话中保存数据。你必须像在“添加购物车”上那样保存它。 以下是我方的两个选择:

  1. 您必须使用AJAX将更改保存到会话。就像你在Test1.php上做的那样。您必须为加号减号操作提供 onclick ,并使用add_cart(p_id="")调用ajax_cart.php来保存更改。
  2. 通过您正在进行的帖子提交将更改保存到Test3.php中的会话。
  3. <强> Test2.php

    <?php 
    session_start();
    include('connection.php');
     ?>
    
    <!doctype html>
    <html lang="en">
    <head>    
          <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
    
                    <!-- table section ends here -->
    
                        <?php if(!empty($_SESSION['product_cart'])){?>
                        <form action="test3.php" method="post">
                        <?php  foreach($_SESSION['product_cart'] as $key=>$product):?>
                          <div class="product-snipet">
                                    <div class="sp-quantity">
                                        <div class="sp-minus fff"><a class="eee" href="javascript:void(0)" data-multi="-1">-</a></div>
                                        <div class="sp-input">
                                            <input type="text" class="quntity-input" name="quantity[]" value="<?php echo $product['quantity'];?>" />
    										<input type="hidden" name="p_id[]" value="<?php echo $key;?>" />
                                        </div>
                                        <div class="sp-plus fff"><a class="eee" href="javascript:void(0)" data-multi="1">+</a></div>
                                    </div>
                                  </div>
                                <?php endforeach;?>
                                <input type="submit" name="submit" class="active" value="Proceed to checkout">
                         </form>
                        <?php }else{echo "<h2 style='font-size:22px'>Cart is empty</h2>";}
                        ?>
             
    
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
        <script type="text/javascript">
            /*increase the product qty*/
      updateTotal();
    $('a.eee').click(function() {
    
      var $productContainer = $(this).closest('div.sp-quantity');
      var $pro_list = $(this).closest('tr.pro-list');
      var productPrice = parseFloat($pro_list.find('span.price_cal').text());
      var $quantityInput = $productContainer.find('input.quntity-input');
      var newQuantity = parseFloat($quantityInput.val()) + parseFloat($(this).data('multi'));
    
      if (newQuantity >= 1) {
        // Refresh quantity input.
        $quantityInput.val(newQuantity);
    
        // Refresh total div.
        var lineTotal = productPrice * newQuantity;
        $pro_list.find('td.total_amount').html('&#36;' + lineTotal);
        $pro_list.find('td.total_amount').data('price', lineTotal); //update data-price
      }
      updateTotal();
    });
    
    function updateTotal() {
      var subTotal = 0;
      var currencySymbol = "$";
      //start getting the total amounts from each product row.
      //add them as a subtotal.
      $("tr.pro-list > td.total_amount").each(function(index, element) {
        subTotal += parseFloat($(element).data("price")); //more secure to use data!
      });
    
      var total = subTotal + $("tr.pro-list.ship > td[data-price]").data("price");
      $("tr.pro-list.sub > td.subtotal").html(currencySymbol + "" + subTotal);
      $("tr.pro-list.total > td.total").html(currencySymbol + "" + total);
    }
     
    	</script>
    </body>
    </html>

    <强> Test3.php

    <?php 
    session_start();
    include('connection.php');
    
    if (isset($_POST['quantity']) && isset($_POST['p_id'])) {
    	foreach($_POST['p_id'] as $key => $val) {
    		if(isset($_SESSION['product_cart']) && isset($_SESSION['product_cart'][$val]))
    		{
    			$p_id	=	$val;
    			$quantity	=	$_POST['quantity'][$key];
    			$currentprice	=	$_SESSION['product_cart'][$p_id]['p_currentprice'];
    
    			$_SESSION['product_cart'][$p_id]['p_total'] = ($currentprice*$quantity);
    			$_SESSION['product_cart'][$p_id]['quantity'] = $quantity;
    		}
    	}
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
    	<title></title>
    </head>
    <body>
    	 <?php 
             if(!empty($_SESSION['product_cart'])): foreach($_SESSION['product_cart'] as $key=>$product): ?>
               <b class="circle-qty"><?php echo $product['quantity'];?></b>
               <input type="hidden" name="o_product_qty[]" value="<?php echo $product['quantity'];?>"> 
               <?php endforeach;?>
               <?php endif;?> 
    
    </body>
    </html>

答案 1 :(得分:0)

首先,您的表单输入字段没有name属性。

add name filed

将其更改为以下内容。

替换test2.php中的输入

<input type="text" name="quantity" class="quntity-input" value="<?php echo 
$product['quantity'];?>" />

然后在test3.php中你可以像那样访问它

$quantity = $_POST['quantity'];

您可以根据自己的需要进行修改。

要在test3.php中输出正确的值,请尝试不使用会话

<input type="hidden" name="o_product_qty[]" value="<?php echo $quantity;?>">

如果你真的想使用会话,你可以在session_start()函数之后立即分配这个帖子值

enter image description here

NB!没有验证,所以在开发之后你应该考虑sql注入和这样的东西

答案 2 :(得分:0)

你得到了未定义的索引,因为$ p_id是在if中定义的,并在if条件下使用它。请更正如下。

<?php 
    session_start();
    include('connection.php');

    if (isset($_POST['quantity']) && isset($_POST['p_id'])) {
        foreach($_POST['p_id'] as $key => $val) {
            $p_id   =   $val;
            if(isset($_SESSION['product_cart']) && isset($_SESSION['product_cart'][$p_id]))
            {
                $quantity   =   $_POST['quantity'][$key];
                $currentprice   =   $_SESSION['product_cart'][$p_id]['p_currentprice'];

                $_SESSION['product_cart'][$p_id]['p_total'] += ($currentprice*$quantity);
                $_SESSION['product_cart'][$p_id]['quantity'] += $quantity;
            }
        }
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
         <?php 
             if(!empty($_SESSION['product_cart'])): foreach($_SESSION['product_cart'] as $key=>$product): ?>
               <b class="circle-qty"><?php echo $product['quantity'];?></b>
               <input type="hidden" name="o_product_qty[]" value="<?php echo $product['quantity'];?>"> 
               <?php endforeach;?>
               <?php endif;?> 

    </body>
    </html>