zoukankan      html  css  js  c++  java
  • session讲解(二)——商城购物车练习

    网上商城中“添加商品到购物车”是主要功能之一,所添加的商品都存到了session中,主要以二维数组的形式存储在session中,在这里我们将以买水果为例

    第一:整个水果商品列表

    <body>
    <h1>水果列表</h1>
    <table width="100%" border="1" cellpadding="0" cellspacing="0">
       <tr>
          <td>水果名称</td>
          <td>水果价格</td>
          <td>水果产地</td>
          <td>水果库存</td>
          <td>操作</td>
       </tr>
    <?php
    include("../DBDA.class.php");
    $db=new DBDA();
    
    $sql="select * from fruit";
    
    $attr=$db->Query($sql);
    
    foreach($attr as $v)
    {
    	echo "<tr>
    	      <td>{$v[1]}</td>
    		  <td>{$v[2]}</td>
    		  <td>{$v[3]}</td>
    		  <td>{$v[4]}</td>
    		  <td><a href='addgwc.php?ids=$v[0]'>加入购物车</a></td>
    		  </tr>";
    }
    
    ?>
    </table>
    <a href="gouwuche.php">查看购物车</a>
    </body>
    

      

    第二:点击“加入购物车时”,后台运行的代码(重要)

    <?php
    session_start();
    
    $ids = $_GET["ids"];
    
    
    //如果第一次点击
    if(empty($_SESSION["sg"]))
    {
    	$attr = array(array($ids,1));
    	$_SESSION["sg"] = $attr;
    }
    else
    {
    	//第n次点击,n!=1
    	$attr = $_SESSION["sg"];
    	
    	//判断该水果师是否已经存在
    	if(iscunzai($ids))  //该水果存在
    	{
    		foreach($attr as $k=>$v)
    		{
    			if($v[0]==$ids)
    			{
    				$attr[$k][1] = $v[1]+1;
    			}
    		}
    		
    		$_SESSION["sg"] = $attr;
    	}
    	else     //该水果不存在
    	{
    		$arr = array($ids,1);
    		array_push($attr,$arr);
    		
    		$_SESSION["sg"] = $attr;
    	}
    
    }
    
    
    //判断该水果师是否已经存在,使用到的函数iscunzai()
    function iscunzai($c)
    {
    	$attr = $_SESSION["sg"];
    	
    	$b = false;
    	
    	foreach($attr as $v)
    	{
    		$b = $b || in_array($c,$v);
    	}
    	
    	return $b;
    }
    
    header("location:showlist.php");
    

      

    第三:查看“购物车列表”

    <body>
    <h1>购物车列表</h1>
    <table width="100%" border="1" cellpadding="0" cellspacing="0">
      <tr>
         <td>水果名称</td>
         <td>水果价格</td>
         <td>数量</td>
      </tr>
    <?php
    session_start();
    
    include("../DBDA.class.php");
    $db = new DBDA();
    
    $attr = $_SESSION["sg"];
    
    foreach($attr as $v)
    {
    	$sql = "select Name,Price from fruit where Ids='{$v[0]}'";
    	
    	$arr = $db->Query($sql);
    	
    	echo "<tr>
    	      <td>{$arr[0][0]}</td>
              <td>{$arr[0][1]}</td>
    	      <td>{$v[1]}</td>
    	</tr>";
    }
    
    
    ?>
    </table>
    <a href="showlist.php">水果列表</a>
    </body>
    

      

  • 相关阅读:
    Redis为什么要自己实现一个SDS
    Redis中的数据结构
    编程题
    设计模式-代理模式
    设计模式-原型模式
    设计模式-工厂模式(简单工厂,工厂方法,抽象工厂)
    Redis基础
    Windows提高_1.4进程通信
    Windows提高_1.3文件操作
    Windows提高_1.2遍历进程、遍历模块
  • 原文地址:https://www.cnblogs.com/zst062102/p/5521783.html
Copyright © 2011-2022 走看看