php实现加入书架
实现加入书架功能
在PHP中实现加入书架功能通常涉及数据库操作和用户会话管理。以下是实现这一功能的关键步骤:
数据库设计
创建用户表users和书籍表books,并建立关联表user_bookshelf存储用户收藏的书籍:
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(255) NOT NULL
);
CREATE TABLE books (
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(100) NOT NULL,
author VARCHAR(50) NOT NULL
);
CREATE TABLE user_bookshelf (
user_id INT NOT NULL,
book_id INT NOT NULL,
added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id, book_id),
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (book_id) REFERENCES books(id)
);
用户认证检查
在加入书架前需要验证用户是否已登录:
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
处理加入书架请求
创建处理加入书架的PHP脚本add_to_bookshelf.php:
<?php
session_start();
require 'db_connection.php'; // 数据库连接文件
if (!isset($_SESSION['user_id'])) {
echo json_encode(['success' => false, 'message' => '请先登录']);
exit();
}
if (isset($_POST['book_id'])) {
$userId = $_SESSION['user_id'];
$bookId = $_POST['book_id'];
// 检查是否已加入书架
$checkSql = "SELECT * FROM user_bookshelf WHERE user_id = ? AND book_id = ?";
$stmt = $conn->prepare($checkSql);
$stmt->bind_param("ii", $userId, $bookId);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo json_encode(['success' => false, 'message' => '该书已在书架中']);
exit();
}
// 加入书架
$insertSql = "INSERT INTO user_bookshelf (user_id, book_id) VALUES (?, ?)";
$stmt = $conn->prepare($insertSql);
$stmt->bind_param("ii", $userId, $bookId);
if ($stmt->execute()) {
echo json_encode(['success' => true, 'message' => '成功加入书架']);
} else {
echo json_encode(['success' => false, 'message' => '加入书架失败']);
}
} else {
echo json_encode(['success' => false, 'message' => '无效请求']);
}
?>
前端交互实现
在书籍详情页添加加入书架的按钮,并使用AJAX发送请求:
<button id="addToBookshelf" data-book-id="123">加入书架</button>
<script>
document.getElementById('addToBookshelf').addEventListener('click', function() {
const bookId = this.getAttribute('data-book-id');
fetch('add_to_bookshelf.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'book_id=' + bookId
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert(data.message);
} else {
alert(data.message);
}
});
});
</script>
书架页面展示
创建展示用户书架的页面bookshelf.php:
<?php
session_start();
require 'db_connection.php';
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
$userId = $_SESSION['user_id'];
$sql = "SELECT b.id, b.title, b.author FROM books b
JOIN user_bookshelf ub ON b.id = ub.book_id
WHERE ub.user_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $userId);
$stmt->execute();
$books = $stmt->get_result();
?>
<!DOCTYPE html>
<html>
<head>
<title>我的书架</title>
</head>
<body>
<h1>我的书架</h1>
<ul>
<?php while ($book = $books->fetch_assoc()): ?>
<li>
<?= htmlspecialchars($book['title']) ?> -
<?= htmlspecialchars($book['author']) ?>
</li>
<?php endwhile; ?>
</ul>
</body>
</html>
移除书架功能
添加从书架移除书籍的功能:
// remove_from_bookshelf.php
session_start();
require 'db_connection.php';
if (!isset($_SESSION['user_id'])) {
echo json_encode(['success' => false, 'message' => '请先登录']);
exit();
}
if (isset($_POST['book_id'])) {
$userId = $_SESSION['user_id'];
$bookId = $_POST['book_id'];
$sql = "DELETE FROM user_bookshelf WHERE user_id = ? AND book_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $userId, $bookId);
if ($stmt->execute()) {
echo json_encode(['success' => true, 'message' => '已从书架移除']);
} else {
echo json_encode(['success' => false, 'message' => '移除失败']);
}
}
以上实现涵盖了加入书架功能的核心要素,包括数据库设计、用户认证、前后端交互和书架管理功能。根据实际需求可以进一步扩展功能,如添加分类、阅读进度跟踪等。







