php可动态定制的商城系统
PHP可以用来创建动态定制的商城系统。以下是一个简单的PHP商城系统的示例代码,包括产品列表页、产品详情页和购物车功能:
// 连接数据库
$db = new PDO('mysql:host=localhost;dbname=shop_db;charset=utf8', 'username', 'password');
// 获取所有产品
$stmt = $db->query('SELECT * FROM products');
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 购物车
$cart = array();
// 添加到购物车
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_to_cart'])) {
$product_id = $_POST['product_id'];
if (isset($cart[$product_id])) {
$cart[$product_id]['quantity']++;
} else {
$stmt = $db->prepare('SELECT * FROM products WHERE id = :id');
$stmt->execute(array(':id' => $product_id));
$product = $stmt->fetch(PDO::FETCH_ASSOC);
$cart[$product_id] = array(
'product' => $product,
'quantity' => 1
);
}
}
// 清空购物车
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['clear_cart'])) {
$cart = array();
}
// 产品列表页
<html>
<head>
<title>商城系统 - 产品列表</title>
</head>
<body>
<h1>产品列表</h1>
<?php foreach ($products as $product): ?>
<div>
<h3><?php echo htmlspecialchars($product['name']); ?></h3>
<p><?php echo htmlspecialchars($product['description']); ?></p>
<form method="post" action="">
<input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
<input type="submit" name="add_to_cart" value="加入购物车">
</form>
</div>
<?php endforeach; ?>
<a href="cart.php">查看购物车</a>
</body>
</html>
// 购物车页
<html>
<head>
<title>商城系统 - 购物车</title>
</head>
<body>
<h1>购物车</h1>
<?php if (empty($cart)): ?>
<p>购物车为空。</p>
<?php else: ?>
<?php foreach ($cart as $item): ?>
<div>
<h3><?php echo htmlspecialchars($item['product']['name']); ?></h3>
<form method="post" action="">
<input type="hidden" name="product_id" value="<?php echo $item['product']['id']; ?>">
<label>数量:
<input type="number" name="quantity" value="<?php echo $item['quantity']; ?>" min="1">
</label>
<input t
评论已关闭