[PHP从小白到大牛]-030 PHP-商城项目(六)

登陆状态加入购物车

建立购物车数据表

CREATE TABLE `cart` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `product_id` int(10) unsigned DEFAULT NULL COMMENT '商品id',
  `product_count` int(11) DEFAULT NULL COMMENT '商品数量',
  `user_id` int(10) unsigned DEFAULT NULL COMMENT '用户id',
  `created_at` datetime DEFAULT NULL COMMENT '商品加入购物车的时间',
  PRIMARY KEY (`id`),
  KEY `product_id` (`product_id`),
  KEY `user_id` (`user_id`),
  CONSTRAINT `cart_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`),
  CONSTRAINT `cart_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
复制代码

从详情页加入购物车

  • 获取商品数量和商品id
  • 商品是数量, 不能超过库存
  • 能够经过js来判断, 超过库存, alert弹框, 并修改商品购买数量为库存
// 监听点击加号之后, input框value的变化
var inc_obj = document.getElementsByClassName('inc qtybutton')[0];
var product_count_input = document.querySelector('[name=qtybutton]');
var stock = parseInt(document.querySelector('[name=product_stock]').value);
inc_obj.onclick = function(){
    // 若是大于库存, 弹框报警, 改数据为库存
    var current = parseInt(product_count_input.value);
    if(current > stock){
        alert('商品数量, 不能大于库存!');
        product_count_input.value = stock;
    }
}
复制代码
  • cart_add.php来处理添加购物车的逻辑代码
  • cart.php来处理展现购物车的逻辑代码

D:\php20190701\php_code\0819-24\shop\backend\shop\cart_add.phpjavascript

<?php
session_id() || session_start();
require_once '../tools.func.php';
require_once '../db.func.php';
$prefix = getDBPrefix();
$current_user = getSession('user', 'shop');

if(!empty($_POST)){
	$product_id = $_POST['product_id'];
	$product_count =$_POST['qtybutton'];
}
if(!empty($_GET)){
	$product_id = $_GET['id'];
	$product_count =$_GET['count'];
	$method = 'get';
}

$user_id = $current_user['id'];
// 查询数据库, 若是已经有了, 更新数据
// 若是没有, 插入数据
$sql = "select product_count from {$prefix}cart where product_id = $product_id and user_id = $user_id";
$res = queryOne($sql);
$created_at = date('Y-m-d H:i:s');
if ($res) {
	$new_count = intval($res['product_count'])+intval($product_count);
	$sql = "update {$prefix}cart set product_count = $new_count, created_at = '$created_at' where product_id = $product_id and user_id = $user_id";
}else{
	$sql = "insert into {$prefix}cart(product_id,user_id,product_count,created_at) values($product_id,$user_id,$product_count,'$created_at')";
}
$res = execute($sql);
if (!$res) {
	setInfo('添加购物车失败!!!','cart.php');
}

if (isset($method)) {
	echo "<script>history.go(-1)</script>";
}else{
	header('location:cart.php');	
}
?>
复制代码

从主页经过按钮加入购物车

  • 须要添加pos参数, 来告诉cart_add.php是经过主页过来的数据
<li>
  <a title="加入购物车" href="cart_add.php?id=<?php echo $product['id'];?>&count=1" ><span class="ti-shopping-cart"></span>
  </a>
</li>
复制代码

经过header.php来展现侧边栏的购物车数据

D:\php20190701\php_code\0819-24\shop\backend\shop\header.phpphp

session_id() || session_start();
require_once '../tools.func.php';
require_once '../db.func.php';
$prefix = getDBPrefix();
$current_user = getSession('user', 'shop');

// 查询购物车
$sql = "SELECT {$prefix}product.name, {$prefix}product.price, {$prefix}product.pic, {$prefix}cart.product_count, {$prefix}cart.id FROM {$prefix}product INNER JOIN {$prefix}cart ON {$prefix}cart.product_id = {$prefix}product.id INNER JOIN {$prefix}user ON {$prefix}cart.user_id = {$prefix}user.id where user_id = ".$current_user['id'];


$cart_result = queryAll($sql);
$total_price = 0;
foreach ($cart_result as $key => $cart) {
    $sum = intval($cart['product_count'])*floatval($cart['price']);
    $total_price+=$sum;
    $cart_result[$key]['sum'] = $sum;
}
复制代码
<div class="shp__cart__wrap">
    <?php foreach($cart_result as $cart):?>
    <div class="shp__single__product">
        <div class="shp__pro__thumb">
            <a href="#">
                <img src="<?php echo($cart['pic']); ?>" alt="product images">
            </a>
        </div>
        <div class="shp__pro__details">
            <h2><a href=""><?php echo($cart['name']); ?></a></h2>
            <span class="quantity">数量: <?php echo($cart['product_count']); ?></span>
            <span class="shp__price">¥<?php echo sprintf("%.2f",$cart['sum']); ?></span>
        </div>
        <div class="remove__btn">
            <a href="cart_delete.php?id=<?php echo $cart['id']."&pos=right"; ?>" title="Remove this item"><i class="zmdi zmdi-close"></i></a>
        </div>
    </div>
    <?php endforeach; ?>
</div>
复制代码

经过cart.php来展现购物车数据, 能够使用header.php里面的数据

D:\php20190701\php_code\0819-24\shop\backend\shop\cart.phphtml

<tbody>
  <?php foreach($cart_result as $cart): ?>
  <tr>
    <td class="product-thumbnail">
      <a href="#"
        ><img src="<?php echo($cart['pic']); ?>" alt="product img"
      /></a>
    </td>
    <td class="product-name">
      <a href="#"><?php echo($cart['name']); ?></a>
    </td>
    <td class="product-price">
      <span class="amount">¥<?php echo($cart['price']); ?></span>
    </td>
    <td class="product-quantity">
      <input type="number" value="<?php echo($cart['product_count']); ?>" />
    </td>
    <td class="product-subtotal">
      ¥<?php echo sprintf('%.2f',$cart['sum'])?>
    </td>
    <td class="product-remove">
      <a href="cart_delete.php?id=<?php echo $cart['id']?>">X</a>
    </td>
  </tr>
  <?php endforeach;?>
</tbody>
复制代码

删除购物车数据

  • 须要购物车id
  • 若是是从侧边栏删除, 返回上一页
  • 若是是从cart.php删除, 还返回cart.php

D:\php20190701\php_code\0819-24\shop\backend\shop\cart_delete.phpjava

<?php
session_id() || session_start();
require_once '../tools.func.php';
require_once '../db.func.php';
$prefix = getDBPrefix();
$current_user = getSession('user', 'shop');

$id = $_GET['id'];

$sql = "delete from {$prefix}cart where id = $id";

if (execute($sql)) {
    if (isset($_GET['pos']) && $_GET['pos'] == "right") {
        echo "<script>history.go(-1);</script>";
    } else {
        header('location:cart.php');
    }
}
复制代码
相关文章
相关标签/搜索