php制作简单的购物车
时间: 2023-08-26 17:05:51 浏览: 91
好的,下面是一个简单的 PHP 购物车的示例代码:
1. 首先,创建一个名为 "cart.php" 的文件,并在文件中添加以下代码:
```php
<?php
session_start();
if(isset($_POST['add-to-cart'])) {
$product_id = $_POST['product-id'];
$product_name = $_POST['product-name'];
$product_price = $_POST['product-price'];
$product_quantity = $_POST['product-quantity'];
$_SESSION['cart'][] = array(
'id' => $product_id,
'name' => $product_name,
'price' => $product_price,
'quantity' => $product_quantity
);
}
?>
```
2. 在需要显示购物车的页面上,添加以下代码:
```php
<?php
session_start();
if(!empty($_SESSION['cart'])) {
echo '<table>';
echo '<tr><th>ID</th><th>Name</th><th>Price</th><th>Quantity</th></tr>';
foreach($_SESSION['cart'] as $item) {
echo '<tr>';
echo '<td>' . $item['id'] . '</td>';
echo '<td>' . $item['name'] . '</td>';
echo '<td>' . $item['price'] . '</td>';
echo '<td>' . $item['quantity'] . '</td>';
echo '</tr>';
}
echo '</table>';
} else {
echo 'Your cart is empty';
}
?>
```
3. 在需要添加商品到购物车的页面上,添加以下代码:
```html
<form method="post" action="cart.php">
<input type="hidden" name="product-id" value="1">
<input type="hidden" name="product-name" value="Product 1">
<input type="hidden" name="product-price" value="10">
<label>Quantity: <input type="number" name="product-quantity" value="1"></label>
<button type="submit" name="add-to-cart">Add to cart</button>
</form>
```
这里的示例代码假设您的商品信息是硬编码在代码中的,实际情况下您需要从数据库或其他数据源动态获取商品信息。此外,这只是一个简单的示例代码,实际的购物车可能需要更多的功能和验证。
阅读全文
相关推荐


















