The most commonly used methods for implementing shopping carts include cookies, sessions and saving records to the database. Below I will introduce the simplest method, which is to use cookies as the product record storage library for shopping carts.
PHP shopping cart, there are many online stores on the Internet, how do they implement shopping carts? Most websites use cookies to achieve this. I also wrote a simple example for your reference
Easy implementation of shopping cart using cookies
Database:
The code is as follows |
Copy code |
代码如下 |
复制代码 |
– phpMyAdmin SQL Dump
– version 2.11.9.2
–
– 主机: 127.0.0.1:3306
– 生成日期: 2009 年 12 月 06 日 02:05
– 服务器版本: 5.1.28
– PHP 版本: 5.2.6
SET SQL_MODE=”NO_AUTO_VALUE_ON_ZERO”;
–
– 数据库: `shopper`
–
– ——————————————————–
–
– 表的结构 `shop`
–
CREATE TABLE IF NOT EXISTS `shop` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`price` int(11) NOT NULL,
`title` varchar(110) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;
–
– 导出表中的数据 `shop`
–
INSERT INTO `shop` (`id`, `price`, `title`) VALUES
(1, 100, ‘玉米’),
(2, 200, ‘大豆’),
(3, 500, ‘西瓜’),
(4, 900, ‘冬瓜’),
(5, 800, ‘大米’);
|
– phpMyAdmin SQL Dump
– version 2.11.9.2
–
– Host: 127.0.0.1:3306
– Generated date: December 06, 2009 02:05
– Server version: 5.1.28
– PHP version: 5.2.6
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
–
– Database: `shopper`
–
–————————————————————
–
– Table structure `shop`
–
CREATE TABLE IF NOT EXISTS `shop` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`price` int(11) NOT NULL,
`title` varchar(110) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;
–
– Export data in the table `shop`
–
INSERT INTO `shop` (`id`, `price`, `title`) VALUES
(1, 100, ‘Corn’),
(2, 200, ‘soy’),
(3, 500, ‘watermelon’),
(4, 900, ‘Winter Melon’),
(5, 800, ‘rice’);
|
PHP code file:
The code is as follows
代码如下 |
复制代码 |
/*
作者:简单小屋
QQ群1:32311900(满)
QQ群2:50900416
QQ2:39407******(满)简单小屋
QQ2:8726**** 海角
*/
$conn=mysql_connect(“localhost”,”root”,”");
mysql_select_db(“shopper”,$conn);
mysql_query(“SET NAMES utf8″);
$sql=”SELECT * FROM `shop` WHERE 1 “;
$sql2=mysql_query($sql);
if($_POST[ok]){
$_POST[number]=(int)$_POST[number];
if($_POST[number]>0){
$idid=$_POST[id];
setcookie(“cookie_arr[$idid]“,$_POST[title].”|”.$_POST[number].”|”.$_POST[price].”|”.$_POST[number]*$_POST[price],time()+36000);
header(“location:shop.php”);
}else{
echo “输入的数量不正确. ”;
}
}
if(isset($_COOKIE['cookie_arr'])){
foreach($_COOKIE['cookie_arr'] as $name => $value) {
$value2=explode(“|”,$value);
echo “ID({$name}) — $value2[0] — 数量:$value2[1] – 单价:$value2[2] – 总价格:$value2[3] n”;
}
}
?>
无标题文档
while($row=mysql_fetch_array($sql2)){
?>
}
?>
| |