在PHP中处理博客评论的方法如下:
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
blog_id INT NOT NULL,
username VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
<form action="submit_comment.php" method="post">
<label for="username">用户名:</label>
<input type="text" name="username" id="username" required>
<br>
<label for="email">电子邮件地址:</label>
<input type="email" name="email" id="email" required>
<br>
<label for="content">评论内容:</label>
<textarea name="content" id="content" required></textarea>
<br>
<input type="submit" value="提交评论">
</form>
submit_comment.php
的PHP脚本,用于接收表单数据并将其插入到数据库中。<?php
// 连接到数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 获取表单数据
$username = $_POST['username'];
$email = $_POST['email'];
$content = $_POST['content'];
$blog_id = $_GET['id']; // 从博客页面获取博客ID
// 插入评论到数据库
$sql = "INSERT INTO comments (blog_id, username, email, content) VALUES ($blog_id, '$username', '$email', '$content')";
if ($conn->query($sql) === TRUE) {
echo "评论成功提交!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
display_comments.php
的PHP脚本,用于从数据库中获取评论并将其显示在博客文章页面上。<?php
// 连接到数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 获取博客ID
$blog_id = $_GET['id'];
// 从数据库中获取评论
$sql = "SELECT * FROM comments WHERE blog_id=$blog_id ORDER BY created_at DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<div class='comment'>
<h3>" . $row["username"] . "</h3>
<p>" . $row["email"] . "</p>
<p>" . $row["content"] . "</p>
<span>" . $row["created_at"] . "</span>
</div>";
}
} else {
echo "暂无评论";
}
$conn->close();
?>
display_comments.php
脚本嵌入到博客文章的页面上,以显示评论。<div class="comments">
<?php include 'display_comments.php'; ?>
</div>
现在,当用户在博客文章页面上提交评论时,评论将被存储在数据库中,并在页面上显示。