检查这段代码的错误并修改实现与book.php的跳转<?php header("Location: book.php"); //连接数据库 $servername = "127.0.0.12"; $username = "roots"; $password = "1234root"; $dbname = "zkw"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("连接失败: " . mysqli_connect_error()); } //查询图书 $id = $_GET["id"]; $sql = "SELECT * FROM books WHERE id=$id"; $result = mysqli_query($conn, $sql); $row = mysqli_fetch_assoc($result); //检查用户是否登录 session_start(); if (!isset($_SESSION["username"])) { $bookshelf_text = "登录后可以添加到书架"; } else { $username = $_SESSION["username"]; $sql = "SELECT * FROM bookshelf WHERE username='$username' AND book_id=$id"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { $bookshelf_text = "从书架中移除"; } else { $bookshelf_text = "添加到书架"; } } mysqli_close($conn); ?> <!DOCTYPE html> <html> <head> <title><?php echo $row["name"]; ?></title> </head> <body> <h2><?php echo $row["name"]; ?></h2> <p><?php echo $row["description"]; ?></p> <a href="bookshelf.php?action=add&id=<?php echo $id; ?>"><?php echo $bookshelf_text; ?></a> </body> </html>
时间: 2024-02-24 10:53:57 浏览: 170
在代码中,跳转的语句应该放在HTML代码之前,而不是之后。因此,应该将跳转语句移到HTML代码之前,如下所示:
```php
<?php
//连接数据库
$servername = "127.0.0.12";
$username = "roots";
$password = "1234root";
$dbname = "zkw";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
//查询图书
$id = $_GET["id"];
$sql = "SELECT * FROM books WHERE id=$id";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
//检查用户是否登录
session_start();
if (!isset($_SESSION["username"])) {
$bookshelf_text = "登录后可以添加到书架";
} else {
$username = $_SESSION["username"];
$sql = "SELECT * FROM bookshelf WHERE username='$username' AND book_id=$id";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$bookshelf_text = "从书架中移除";
} else {
$bookshelf_text = "添加到书架";
}
}
mysqli_close($conn);
//跳转到book.php页面
header("Location: book.php");
exit();
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo $row["name"]; ?></title>
</head>
<body>
<h2><?php echo $row["name"]; ?></h2>
<p><?php echo $row["description"]; ?></p>
<a href="bookshelf.php?action=add&id=<?php echo $id; ?>"><?php echo $bookshelf_text; ?></a>
</body>
</html>
```
阅读全文