前端增加商品到购物车
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>向后台请求数据</title>
</head>
<body>
<li class="clearfix">
<dd>
<strong>购买数量</strong>
<input name="number" type="text" id="number" value="1" size="4" onblur="" style="border:1px solid #ccc9a4;">
<strong>商品总价</strong><font id="" class="f1">¥<?php echo $data['price']?>元</font>
</dd>
</li>
<li class="padd">
</body>
<a href="javascript:addCart(<?php echo $data['id']?>);">加入购物车</a>
<script type="text/ecmascript"> function addCart(productid){ //ajax请求php脚本完成数据的添加 shop_cart var url="sddCart.php"; var data={"productid":productid,"num":parseInt($('#number').val())}; var success= function (response) { if(response.errno ==0){ alert('加入购物车成功') }else{ alert('加入购物车失败') } } $.post(url,data,success,"json"); } </script>
</html>
后端addCart.php文件更改商品数量
addCart.php
<?php /** * Created by PhpStorm. * User: xue * Date: 2016/4/14 * Time: 11:37 */ //加入购物车操作 //1接受传递过来的参数 $productid=intval($_POST['productid']); $num=intval($_POST['num']); //2准备要添加的购物车数据 session_start(); $userid=$_SESSION['memberid']; try{ $pdo=new PDO("mysql:host=localhost:dbname=food","root","",array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION)); $pdo->query("set names utf8"); $sql="select price from shop_product where id=?"; $stmt=$pdo->prepare($sql); $stmt->execute(array($productid)); $data=$stmt->fetch(PDO::FETCH_ASSOC); $price=$data['price']; $createtime=time(); //3完成购物车数据的添加操作(判断当前用户在购物车中是否已经加入该商品) $sql="select * from shop_cart where productid=? and userid=?"; $stmt=$pdo->prepare($sql); $smtm->execute(array($productid,$userid)); $data=$stmt->fetch(PDO::FETCH_ASSOC); if($data){ $sql="update shop_cart set num=num+? where userid=? and productid=? "; $params=array($productid,$num,$userid); }else{ $sql="insert into shop_cart(productid,num,useid,price,craetetime)values(?,?,?,?,?)"; $params=array($productid,$num,$userid,$price,$createtime); } $stmt-$pdo->prepare($sql); $stmt->execute(array($productid,$num,$price,$createtime)); $rows=$stmt->rowCount(); var_dump($data); }catch (PDOException $e){ echo $e->getMessage(); } //4返回最后添加的结果 if($rows){ $response=array( 'errno'=>0, 'errmsg'=>'success', 'data'=>true, );}else{ $response=array( 'errno'=>-1, 'errmsg'=>"faild", 'data'=>false, ); } echo json_encode($data);