网上书店系统设计与实现,dev代码
时间: 2023-11-12 16:25:50 浏览: 94
这是一个简单的网上书店系统设计与实现的dev代码,使用了PHP和MySQL数据库。
前端代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>网上书店</title>
</head>
<body>
<h1>网上书店</h1>
<nav>
<ul>
<li><a href="index.php">首页</a></li>
<li><a href="cart.php">购物车</a></li>
<li><a href="login.php">登录</a></li>
<li><a href="register.php">注册</a></li>
</ul>
</nav>
<hr>
<h2>图书列表</h2>
<ul>
<?php
// 查询所有图书信息
$sql = "SELECT * FROM books";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "<li>";
echo "<h3>" . $row["title"] . "</h3>";
echo "<p>" . $row["author"] . "</p>";
echo "<p>" . $row["description"] . "</p>";
echo "<p>价格: " . $row["price"] . "元</p>";
echo "<form method='post' action='add_to_cart.php'>";
echo "<input type='hidden' name='book_id' value='" . $row["id"] . "'>";
echo "<input type='number' name='quantity' value='1'>";
echo "<input type='submit' value='加入购物车'>";
echo "</form>";
echo "</li>";
}
mysqli_free_result($result);
mysqli_close($conn);
?>
</ul>
</body>
</html>
```
后端代码:
```php
<?php
// 连接数据库
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "bookstore";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
// 处理加入购物车
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["book_id"]) && isset($_POST["quantity"])) {
$book_id = $_POST["book_id"];
$quantity = $_POST["quantity"];
$sql = "SELECT * FROM books WHERE id=$book_id";
$result = mysqli_query($conn, $sql);
if ($row = mysqli_fetch_assoc($result)) {
$item = array(
"id" => $row["id"],
"title" => $row["title"],
"author" => $row["author"],
"price" => $row["price"],
"quantity" => $quantity
);
if (isset($_SESSION["cart"])) {
$cart = $_SESSION["cart"];
} else {
$cart = array();
}
$cart[$book_id] = $item;
$_SESSION["cart"] = $cart;
header("Location: cart.php");
exit;
}
mysqli_free_result($result);
}
mysqli_close($conn);
?>
```
这段代码实现了以下功能:
1. 查询所有图书信息并展示在网页上。
2. 用户可以选择加入购物车。
3. 处理加入购物车的请求,将商品信息添加到购物车中。
阅读全文