php使用cookie实现购物车

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq635968970/article/details/43406549

查看商城源码时 看到的做下笔记

文件包括: test.php,cart.php

一. test.php(商品显示页面)

<?php
	$cart_list = !empty($_COOKIE['cart_list'])?unserialize($_COOKIE['cart_list']):array();
	//例子使用数组实际会用mysql
	$product_list = array(
		array(
			'pid'   => 1,
			'name' => '商品1号',
			'money' => '10.5元',
			'logo' => ''
		),
		array(
			'pid' =>2,
			'name' => '商品2号',
			'money' => '23.5元',
			'logo' => ''
		)
	);
?>
<!DOCTYPE HTML>
<html>
<head>
	<meta charset="utf-8" />
	<title>cart</title>
	<style type="text/css">
	*{ margin:0;padding:0; }
	.product { border:1px solid #ccc;}
	</style>
</head>
<body>
	<p>购物车(<?php echo !empty($cart_list)?count($cart_list):0; ?>)</p>
	<form method="post" action="cart.php" >
	<input id="p-id" type="hidden" name="id" value=""/>
	<input id="p-name" type="hidden" name="product" value=""/>
	<table class="list">
		<tr>
			<?php foreach($product_list as $v):?>
			<td class="product">
				<img width="180" height="180" src="<?php echo $v['logo']; ?>"/>
				<p>商品名:<?php echo $v['name']; ?></p>
				<p>商品价格:<?php echo $v['money']; ?><p>
				<!--使用两个隐藏域来 设置要提交的数据-->
				<input type="button" onclick="document.getElementById('p-id').value =<?php echo $v['pid'];?>; document.getElementById('p-name').value = '<?php echo $v['name']; ?>'; document.forms[0].submit();" value="加入购物车" />
			</td>
			<?php endforeach; ?>
		</tr>
	</table>
	</form>
</body>
</html></span>
二.cart.php(购物车显示页面)

<?php 
	header('Content-type:text/html; charset=utf-8');
	//查看cookie里面有没有购物车数据 有就返回序列化后的结果
	$cart_list = !empty($_COOKIE['cart_list'])?unserialize($_COOKIE['cart_list']):''; 	
	if(isset($_POST['id']) && isset($_POST['product'])){	
		$id = $_POST['id']; //给每个商品ID一个数组来保存数据
		$cart_list[$id]['name'] = $_POST['product'];
		$cart_list[$id]['id'] = intval($id);
		$cart_list[$id]['time'] = time();
		//设置cookie保存购物车
		setcookie('cart_list', serialize($cart_list), 0, '/');
	}	
?>
<html>
<head>
	<meta charset="utf-8" />
	<title>购物车列表</title>
	<style type="text/css">
	*{margin:0; padding:0;}
	</style>
</head>
<body>
	<table>
		<tr>
			<th>商品名称</th>
			<th>加入时间</th>
		</tr>
		<?php if(is_array($cart_list)){ foreach($cart_list as $v):?>
		<tr>
			<td><?php echo $v['name']; ?></td>
			<td><?php echo $v['time']; ?></td>
		</tr>
		<?php endforeach; }?>
	</table>
</body>
</html></span>

效果图:


猜你喜欢

转载自blog.csdn.net/qq635968970/article/details/43406549