开发商城或者学习当中,购物车练习是一个行之有效的锻炼方式。第一:能锻炼PHP逻辑思维 第二:能锻炼HTML&&JQ&&AJAX联合练习。
下面是我做购物车(商品可以多规格)的经验:
第一步设计数据表结构:
CREATE TABLE `tp_goods_cart` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`openid` varchar(100) DEFAULT '',
`goodsid` int(11) DEFAULT '0',//商品表ID
`total` int(11) DEFAULT '0',
`marketprice` decimal(10,2) DEFAULT '0.00',
`deleted` tinyint(1) DEFAULT '0',
`optionid` int(11) DEFAULT '0', //针对多规格
`createtime` int(11) DEFAULT '0',
`selected` tinyint(1) DEFAULT '1',
`merchid` int(11) DEFAULT '0', //针对多商户
`selectedadd` tinyint(1) DEFAULT '1',
PRIMARY KEY (`id`),
KEY `idx_uniacid` (`uniacid`),
KEY `idx_goodsid` (`goodsid`),
KEY `idx_openid` (`openid`),
KEY `idx_deleted` (`deleted`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
第二步:编辑PHP代码,使用演示数组测试
在进行商品添加进购物车时,需要组织好数据:商品信息goodsid、marketprice、total(选择的数量)、optionid选择的规格,对已经购买的商品deleted字段加标志
添加购物车代码示例:
public function add()
{
$id = intval($_GET['id']);
$total = intval($_GET['total']);
($total <= 0) && ($total = 1);
$optionid = intval($_GET['optionid']);
$goods = pdo_fetch('select id,marketprice isverify, `type`,merchid, cannotrefund from ' . tablename('tp_goods') . ' where id=:id and limit 1', array(':id' => $id));
if (empty($goods))
{
show_json(0, '商品未找到');
}
$member = session('userD');;
if (($goods['isverify'] == 2) || ($goods['type'] == 2) || ($goods['type'] == 3) || !(empty($goods['cannotrefund'])))
{
show_json(0, '此商品不可加入购物车<br>请直接点击立刻购买');
}
$data = pdo_fetch('select id,total,diyformid from ' . tablename('ewei_shop_member_cart') . ' where goodsid=:id and openid=:openid and optionid=:optionid and deleted=0 limit 1', array(':openid' => $_W['openid'], ':optionid' => $optionid, ':id' => $id));
if (empty($data))
{
$data = array('merchid' => $goods['merchid'], 'openid' => $_W['openid'], 'goodsid' => $id, 'optionid' => $optionid, 'marketprice' => $goods['marketprice'], 'total' => $total, 'selected' => 1 'createtime' => time());
pdo_insert('tp_goods_cart', $data);
}
else
{
$data['total'] += $total;
pdo_update('ewei_shop_member_cart', $data, array('id' => $data['id']));
}
$cartcount = pdo_fetchcolumn('select sum(total) from ' . tablename('tp_goods_cart') . ' where openid=:openid and deleted=0 limit 1', array(':openid' => $member['openid']));
show_json(1, array('isnew' => false, 'cartcount' => $cartcount));
}
第三部:编写页面
对购物车多商品情况,设置选择择项、可提交多个商品形成一个订单。对于购物车联系项目涉及面比较多,涉及到订单、涉及到商品,举例子相对艰难,优睿素材网中有相关的源码,觉得能借鉴可以下载来学习!