在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>
現在,當用戶在博客文章頁面上提交評論時,評論將被存儲在數據庫中,并在頁面上顯示。