Home  >  Article  >  Backend Development  >  How to implement shopping cart in php using session

How to implement shopping cart in php using session

藏色散人
藏色散人Original
2020-08-29 09:20:533678browse

php uses session to implement the shopping cart method: first create the front-end code to implement the action of adding to the shopping cart; then implement the logical judgment of the shopping cart data in the PHP file; then load the list according to the data; and finally implement it through functions such as unset Just delete the product or calculate the amount.

How to implement shopping cart in php using session

# Recommended: "

PHP Video Tutorial

PHP uses session to achieve the shopping cart effect (click the button to add data, generate a list based on the data, delete the selected product, and calculate the amount when the button is clicked)

Effect Chart

There is a lot of code, intercept a part

Add to shopping cart (click the button to add session data)

##

    // 加入购物车
    function addshopping() {
      <?php
      $db = db($_GET[&#39;db&#39;]);
      $id = $formatData[&#39;id&#39;];
      $user = $formatData[&#39;user&#39;];
      // 当购物车没有时,即没有session数据时
      if (empty($_SESSION[&#39;gwc&#39;])) {
        $arr = array(array(&#39;user&#39; => $user, &#39;db&#39; => $db, &#39;id&#39; => $id, &#39;num&#39; => 1));
        $_SESSION[&#39;gwc&#39;] = $arr;
      } else {
        // 当购物车有数据时
        $arr = $_SESSION["gwc"];
        $order = false;
        foreach ($arr as $key => $value) {
          // 如果数据中有了这个数据
          if ($value[&#39;user&#39;] == $user && $value[&#39;db&#39;] == $db && $value[&#39;id&#39;] == $id) {
            $index = $key;  //保存这个相同数据的下标,以便操作
            $order = true;	
            //定义一个变量,看是佛有相同的数据,需要注意的是,不能再这个if语句中else,否则后面的语句
            //虽然会使数量加一,但是还是会多创建一条数据,为什么,自己想想就能明白,只是当时当局者迷
          }
        }
        if ($order) {
          // 如果该商品在购物车存在,让数量加1
          $arr[$index][&#39;num&#39;]++;
        } else {
          // 如果该商品购物车里面不存在,造一个一维数组扔到二维里面
          $arr[] = array(&#39;user&#39; => $user, &#39;db&#39; => $db, &#39;id&#39; => $id, &#39;num&#39; => 1);
        }
        $_SESSION["gwc"] = $arr;
      }

      ?>
      console.log(&#39;addshopping&#39;);
    }
How to implement shopping cart in php using sessionLoad the list according to the data

    <!-- 购物车列表 -->
    <?php
    foreach ($_SESSION[&#39;gwc&#39;] as  $dataList) {
        $clean = array();
        $clean[&#39;user&#39;] = $dataList[&#39;user&#39;];
        $clean[&#39;db&#39;] = $dataList[&#39;db&#39;];
        $clean[&#39;id&#39;] = $dataList[&#39;id&#39;];
        $clean[&#39;num&#39;] = $dataList[&#39;num&#39;];

        $res = $conn->fetchRow("SELECT * FROM {$clean[&#39;db&#39;]}  WHERE id={$clean[&#39;id&#39;]}");
        $clean[&#39;title&#39;] = $res[&#39;title&#39;];
        $clean[&#39;price&#39;] = $res[&#39;price&#39;];
        $clean[&#39;face&#39;]  = $res[&#39;face&#39;];

    ?>
        <p class="weui-content">
            <p class="weui-panel weui-panel_access">

                <p class="weui-panel__hd"><span><?php echo  $clean[&#39;user&#39;]; ?> </span><a href="javascript:void(0)" class="wy-dele"><!-- 删除 --></a></p>

                <p class="weui-panel__bd">
                    <p class="weui-media-box_appmsg pd-10">
                        <p class="weui-media-box__hd check-w weui-cells_checkbox">
                            <label class="weui-check__label" for="cart-<?php echo $clean[&#39;db&#39;] . &#39;-&#39; . $clean[&#39;id&#39;] ?>">
                     
                                <p class="weui-cell__hd cat-check">
                                    <input type="checkbox" class="weui-check" name="cartpro" id="cart-<?php echo $clean[&#39;db&#39;] . &#39;-&#39; . $clean[&#39;id&#39;] ?>"><i class="weui-icon-checked"></i>
                                </p>
                            </label>
                        </p>
                        <p class="weui-media-box__hd"><a href="pro_info.php?db=<?php echo  $clean[&#39;db&#39;]; ?>&id=<?php echo  $clean[&#39;id&#39;]; ?>"><img  class="weui-media-box__thumb" src="<?php echo  $clean[&#39;face&#39;];  ? alt="How to implement shopping cart in php using session" >" alt=""   style="max-width:90%"></a></p>
                        <p class="weui-media-box__bd">
                            <h1 class="weui-media-box__desc"><a href="pro_info.php?db=<?php echo  $clean[&#39;db&#39;]; ?>&id=<?php echo  $clean[&#39;id&#39;]; ?>" class="ord-pro-link"><?php echo  $clean[&#39;title&#39;];  ?></a></h1>
                            <p class="weui-media-box__desc">规格:<span>红色</span>,<span>23</span></p>
                            <p class="clear mg-t-10">
                                <p class="wy-pro-pri fl">¥<em class="num font-15 price"><?php echo  $clean[&#39;price&#39;];  ?></em></p>
                                <p class="pro-amount fr">
                                    <!-- 购买的数量 -->
                                    <input type="hidden" name="" class="datanum" value="<?php echo  $clean[&#39;num&#39;]; ?>">
                                    <!-- 提交删除的数据 -->
                                    <input type="hidden" name="" class="rmdata" value="shopping.php?db=<?php echo  $clean[&#39;db&#39;]; ?>&id=<?php echo  $clean[&#39;id&#39;];?>">
                                    <p class="Spinner"></p>
                                </p>
                            </p>
                        </p>
                    </p>
                </p>


            </p>
        </p>
    <?php }
    ?>

Delete the selected product

// echo &#39;<pre class="brush:php;toolbar:false">&#39;;// print_r($_SESSION[&#39;gwc&#39;]);// echo &#39;
';if(isset($_GET['db']) && isset($_GET['id'])){     $dataArr = $_SESSION['gwc'];     foreach ($dataArr as $key => $value) {         if($value['db'] == $_GET['db'] && $value['id'] == $_GET['id']){             unset($dataArr[$key]);         }     }     $_SESSION['gwc'] = $dataArr;     header("Location:shopping.php");}// echo '
';// print_r( $dataArr);// echo '
';

Amount calculation

    <!-- 金额计算 -->
    <script>
        window.onload = function() {
            var cartproAll = document.querySelectorAll(&#39;input[name=cartpro]&#39;);	
            var datanum = document.querySelectorAll(&#39;.datanum&#39;);   
            var numAll = document.querySelectorAll(&#39;.Amount&#39;);
            var DisDe  = document.querySelectorAll(&#39;.DisDe&#39;);
            var Increase  = document.querySelectorAll(&#39;.Increase&#39;);

            //  购买数量的多少
            numAll.forEach((item,i) => {
                item.value = datanum[i].value;
            })

            // 点击加号
            DisDe.forEach((item, i) => {
                item.onclick = function() {
                    computedPrice();
                }
            })
            // 点击减号
            Increase.forEach((item, i) => {
                item.onclick = function() {
                    computedPrice();
                }
            })
            // 点击单选时计算金额
            cartproAll.forEach((item, i) => {
                item.onclick = function() {
                    computedPrice();
                }
            })
        }
        function computedPrice(){
            var cartproAll = document.querySelectorAll(&#39;input[name=cartpro]&#39;);      //获取是否点击
            var price = document.querySelectorAll(&#39;.price&#39;);                        //价钱
            var price_total = document.querySelector(&#39;.price_total&#39;);               //价钱总数   
            var numAll = document.querySelectorAll(&#39;.Amount&#39;);                      //数量
            var total = 0;
            price_total.innerHTML = 0;
            cartproAll.forEach((item, i) => {
                if (item.checked == true) {
                        total += parseFloat(price[i].innerHTML) * parseFloat(numAll[i].value);
                    }
            })
            price_total.innerHTML = total;
        }
    </script>

The above is the detailed content of How to implement shopping cart in php using session. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn