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>

  

 

posted @ 2016-05-23 22:36  坏小子1993  阅读(258)  评论(0编辑  收藏  举报