在Web开辟中,批评体系是进步用户互动跟网站活泼度的重要功能。PHP作为一种风行的效劳器端剧本言语,常用于构建多级批评体系。本文将深刻剖析PHP多级批评体系的实现道理,并供给实战技能,帮助开辟者轻松控制这一功能。
多级批评体系容许用户对批评停止复兴,构成层级构造。平日,每个批评都有一个独一的ID,用于标识其地位跟层级。以下是一个简单的多级批评体系构造:
为了存储批评数据,我们须要计整齐个数据库表。以下是一个简单的批评表构造:
CREATE TABLE comments (
id INT(11) NOT NULL AUTO_INCREMENT,
parent_id INT(11) NOT NULL DEFAULT '0',
article_id INT(11) NOT NULL,
user_id INT(11) NOT NULL,
content TEXT NOT NULL,
add_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY parent_id (parent_id),
KEY article_id (article_id),
KEY user_id (user_id)
);
在这个表中,parent_id
用于存储父批评的ID,当 parent_id
为0时,表示该批评是一级批评。
<?php
// 连接数据库
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
// 获取批评数据
$article_id = $_POST['article_id'];
$user_id = $_SESSION['user_id'];
$content = $_POST['content'];
// 拔出批评
$sql = "INSERT INTO comments (parent_id, article_id, user_id, content) VALUES (0, $article_id, $user_id, '$content')";
$mysqli->query($sql);
?>
<?php
// 连接数据库
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
// 获取文章ID
$article_id = $_GET['article_id'];
// 获取批评列表
$sql = "SELECT * FROM comments WHERE article_id = $article_id ORDER BY add_time DESC";
$result = $mysqli->query($sql);
// 递归获取子批评
function getComments($comments, $parent_id = 0) {
$output = [];
foreach ($comments as $comment) {
if ($comment['parent_id'] == $parent_id) {
$output[] = $comment;
$output = array_merge($output, getComments($comments, $comment['id']));
}
}
return $output;
}
// 获取全部批评
$comments = getComments($result->fetch_all(MYSQLI_ASSOC));
?>
<ul>
<?php foreach ($comments as $comment): ?>
<li>
<p>用户:<?php echo $comment['user_id']; ?></p>
<p>批评内容:<?php echo $comment['content']; ?></p>
<?php if (count($comment['children']) > 0): ?>
<ul>
<?php foreach ($comment['children'] as $child): ?>
<li>
<p>复兴用户:<?php echo $child['user_id']; ?></p>
<p>复兴内容:<?php echo $child['content']; ?></p>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
经由过程本文的剖析,信赖你曾经对PHP多级批评体系的实现有了更深刻的懂得。在现实开辟中,根据项目须要,一直优化跟调剂,才干构建出功能完美、机能优良的批评体系。