关于php实现添加购物车功能,具体代码如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
<!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>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
<!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>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
<?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" );
|
以上所述是小编给大家介绍的PHP实现添加购物车功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:http://www.cnblogs.com/jc535201285/archive/2017/03/06/6508829.html