1.提交数据@H_502_2@:
<a href="javascript:addCate(<?PHP echo $data['id']?>);">提交</a>
<script type=text/javascript>
function addCate(productid)
{
var url=ddCate.PHP;//提交地址
//确定需要传递的值,产品id 数量,数量根据输入框id得到并转换为整数
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>
2.创建addCate.PHP表单加入购物车操作@H_502_2@
//01.接收传递过来的参数@H_502_2@
$productid=intval($_POST['productid']);//接受的为数据 可以进行整形约束
$num=intval($_POST['num']);
session_start();
$userid=$_SESSION['userid'];//得到用户id
try{
$pdo=new PDO("MysqL:host=localhost;dbname=username","root",array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
$pdo->query('set names utf8);
$sql="select price from shop_productwhere id=?";
$stmt=$pdo->prepare($sql);
$stmt->execute(array($productid));
$data=$stmt->fetch(PDO::FETCH_ASSOC);
$price=$data['price'];
$createtime=time();
$sql="insert into shop_cart(productid num userid price createtime)valur(?,?,?)";
$stmt=$pdo->prepare($sql);
$stmt->execute(array($product,$num,$price,$userid,$createtime));
$rows=$stmt->rowcount();
}catch(PDO::Exception $e)
{
echo $e->getMessage();
}
if($rows){
$response=array(
'errno'=>0;
'errmsg'=>'success’,
‘data'=>true,
)
}else{
$response=array(
'errno'=>-1;
'errmsg'=>'fail’,
‘data'=>fals,
)
}
echo json_encode($response);
3.数据表@H_502_2@
shop_cart:@H_502_2@
id (bigint(20)),product_id(bigint(20)),userid(bigint(20)@H_502_2@),num(int(10)默认1),price(float8,2),createtime(int(10)).
@H_502_2@
shop_product:@H_502_2@
原文链接:https://www.f2er.com/ajax/161809.html