php添加购物车

<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>

<h1>商品列表</h1>

<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
<td>水果代号</td>
<td>水果名称</td>
<td>水果价格</td>
<td>水果产地</td>
<td>水果库存</td>
<td>操作</td>
</tr>

<?php
session_start();
include("../fengzhuang/DBDA.class.php");
$db = new DBDA();

$sql = "select * from fruit";
$arr = $db->Query($sql);
foreach($arr as $v)
{
echo "<tr>
<td>{$v[0]}</td>
<td>{$v[1]}</td>
<td>{$v[2]}</td>
<td>{$v[3]}</td>
<td>{$v[4]}</td>
<td><a href='add.php?ids={$v[0]}'>加入购物车</a></td>
</tr>";
}
?>

</table>

<?php
var_dump($_SESSION["gwc"]);
?>


</body>
</html>





<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<h1>购物车详情</h1>

<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
<td>水果代号</td>
<td>购买数量</td>
<td>操作</td>
</tr>

<?php
session_start();

$arr = array();
if(!empty($_SESSION["gwc"]))
{
$arr = $_SESSION["gwc"];
}

foreach($arr as $v)
{
echo "<tr>
<td>{$v[0]}</td>
<td>{$v[1]}</td>
<td></td>
</tr>";
}
?>

</table>

</body>
</html>





<?php
session_start();

$ids = $_GET["ids"];

/*$arr = array(
array("k001",10),
array("k002",2),
array("k003",5)
);*/

//1.第一次点击添加购物车
//2.如果购物车中没有该商品
//3.如果购物车中有该商品

if(empty($_SESSION["gwc"]))
{
//1.第一次点击添加购物车
$arr = array(
array($ids,1)
);
$_SESSION["gwc"]=$arr;
}
else
{
//不是第一次点击
//判断购物车中是否存在该商品
$arr = $_SESSION["gwc"];

$chuxian = false;
foreach($arr as $v)
{
if($v[0]==$ids)
{
$chuxian = true;
}
}

if($chuxian)
{
//3.如果购物车中有该商品
/*foreach($arr as $v)
{
if($v[0]==$ids)
{
$v[1] = $v[1]+1;
}
}*/

for($i=0;$i<count($arr);$i++)
{
if($arr[$i][0]==$ids)
{
$arr[$i][1]+=1;
}
}

$_SESSION["gwc"] = $arr;
}
else
{
//2.如果购物车中没有该商品
$asg = array($ids,1);
$arr[] = $asg;
$_SESSION["gwc"] = $arr;
}

}

header("location:main.php");
posted @ 2017-03-06 10:42  周全264  阅读(475)  评论(0编辑  收藏  举报