<?php
session_start();
class
Cart
{
public
$pdo
= null;
public
function
__construct(
$config
)
{
$host
=
$config
['host'];
$user
=
$config
['user'];
$db
=
$config
['db'];
$pwd
=
$config
['pwd'];
if
(
empty
(
$_SESSION
['user_id'])) {
return
show(0, '请先登录');
}
try
{
$this
->pdo =
new
PDO(
"mysql:host=$host;dbname=$db"
,
"$user"
,
"$pwd"
,
array
(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$this
->pdo->query(
"set names utf8"
);
}
catch
(PDOException
$e
) {
echo
$e
->getMessage();
}
}
public
function
add_cart(
$productid
,
$num
)
{
$sql
=
"select price from shop_product where id=?"
;
$stmt
=
$this
->pdo->prepare(
$sql
);
$stmt
->execute(
array
(
$productid
));
$data
=
$stmt
->fetch(PDO::FETCH_ASSOC);
$price
=
$data
['price'];
$createtime
= time();
$sql
=
"select * from shop_cart where productid=? and userid=?"
;
$stmt
=
$this
->pdo->prepare(
$sql
);
$stmt
->execute(
array
(
$productid
,
$_SESSION
['user_id']));
$data
=
$stmt
->fetch(PDO::FETCH_ASSOC);
if
(
$data
) {
$sql
=
"update shop_cart set num=num+? where userid=? and productid=?"
;
$params
=
array
(
$num
,
$_SESSION
['user_id'],
$productid
);
}
else
{
$sql
=
"insert into shop_cart(productid,num,userid,price,createtime) values(?,?,?,?,?)"
;
$params
=
array
(
$productid
,
$num
,
$_SESSION
['user_id'],
$price
,
$createtime
);
}
$stmt
=
$this
->pdo->prepare(
$sql
);
$stmt
->execute(
$params
);
$rows
=
$stmt
->rowCount();
return
$rows
?
show(1, 'ok',
$rows
) :
show(0, 'fail');
}
public
function
change_num(
$productid
,
$num
)
{
$sql
=
"update shop_cart set num=? where userid=? and productid=?"
;
$stmt
=
$this
->pdo->prepare(
$sql
);
$stmt
->execute(
array
(
$num
,
$_SESSION
['user_id'],
$productid
));
$rows
=
$stmt
->rowCount();
return
$rows
?
show(1, 'ok',
$rows
) :
show(0, 'fail');
}
public
function
clear_cart()
{
$sql
=
"delete from shop_cart where userid=?"
;
$stmt
=
$this
->pdo->prepare(
$sql
);
$this
->pdo->execute(
array
(
$this
->user_id));
$rows
=
$stmt
->rowCount();
return
$rows
?
show(1, 'ok',
$rows
) :
show(0, 'fail');
}
public
function
remove_cart(
$productid
)
{
$sql
=
"delete from shop_cart where productid=? and userid=?"
;
$stmt
=
$this
->pdo->prepare(
$sql
);
$stmt
->execute(
array
(
$productid
,
$_SESSION
['user_id']));
$rows
=
$stmt
->rowCount();
return
$rows
?
show(1, 'ok',
$rows
) :
show(0, 'fail');
}
}
function
show(
$status
,
$message
,
$data
=
array
())
{
$result
=
array
(
'status' =>
$status
,
'message' =>
$message
,
'data' =>
$data
);
exit
(json_encode(
$result
));
}
$user
= [
'host' => '',
'user' => 'root',
'pwd' => 'root',
'db' => 'shop',
];
$productid
=
intval
(
$_POST
['productid']);
$num
=
intval
(
$_POST
['num']);
$cart
=
new
Cart(
$user
);
$cart
->add_cart(
$productid
,
$num
);
$cart
->remove_cart(
$productid
);
$cart
->clear_cart();
?>