Jifunze kutengeneza multi-level (nested) comment system kama Facebook na YouTube—comments, replies, na replies za replies bila kikomo. Rahisi, safi na scalable.

✅ 1. Tengeneza Table ya Comments (MySQL)
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
post_id INT NOT NULL,
user_name VARCHAR(100),
comment TEXT,
parent_id INT DEFAULT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);


Maana ya columns:

post_id – comment imewekwa kwenye post ipi

parent_id – ikiwa ni reply, humu ndipo huunganishwa na comment ya juu

comment – maoni yenyewe

✅ 2. Kuhifadhi Comment au Reply
function add_comment($conn, $post_id, $user_name, $comment, $parent_id = null) {
$sql = "INSERT INTO comments (post_id, user_name, comment, parent_id)
VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("issi", $post_id, $user_name, $comment, $parent_id);
return $stmt->execute();
}


Kutumia:

add_comment($conn, 1, "Faustine", "Hii post ni nzuri!", null); // comment ya kawaida
add_comment($conn, 1, "John", "Asante!", 5); // reply ya comment yenye ID 5

✅ 3. Kupata Comments kwa Post
function get_comments($conn, $post_id) {
$sql = "SELECT * FROM comments WHERE post_id = ? ORDER BY created_at ASC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $post_id);
$stmt->execute();
return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

✅ 4. Kutengeneza Multi-Level Tree (PHP Recursive Function)
function build_tree($comments, $parent_id = null) {
$branch = [];

foreach ($comments as $comment) {
if ($comment['parent_id'] == $parent_id) {
$children = build_tree($comments, $comment['id']);
if ($children) {
$comment['replies'] = $children;
}
$branch[] = $comment;
}
}
return $branch;
}

✅ 5. Kuonyesha Comments Kwenye HTML
function render_comments($tree) {
echo "<ul>";
foreach ($tree as $c) {
echo "<li>";
echo "<strong>{$c['user_name']}</strong>: {$c['comment']} <br>";
echo "<a href='#' class='reply-btn' data-id='{$c['id']}'>Reply</a>";

if (!empty($c['replies'])) {
render_comments($c['replies']); // recursion
}

echo "</li>";
}
echo "</ul>";
}

🔄 6. Kuisambaza kwenye Page (Main)
$comments = get_comments($conn, $post_id);
$tree = build_tree($comments);
render_comments($tree);

🎯 Faida za Multi-Level Comment System

Support ya unlimited replies

Inafanana na YouTube, Facebook, Reddit

Safi kuona discussion structure

Inafaa kwa blogs, forums, school portals, & systems za kujifunza

🔗 Links Za Kujifunza Zaidi

🌐 Faulink Official Website:
https://www.faulink.com/

📘 Jifunze Web Design & Programming (Tutorials / Mifumo):
https://www.faulink.com/excel_mifumo.php

📲 Piga / WhatsApp kwa msaada wa haraka:
https://wa.me/255693118509