如何为现有PHP发帖系统添加社区功能,实现帖子按社区分区展示
Hey there! Let's walk through adding that Communities feature step by step. I'll break this down into manageable parts so you can integrate it smoothly with your existing code.
First, we need to add tables to support communities and link posts to them. Run these SQL queries in your database:
-- Create communities table to store community details CREATE TABLE communities ( community_id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL UNIQUE, description TEXT, created_by INT NOT NULL, date_created DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (created_by) REFERENCES users(uid) ); -- Add community_id column to posts table to link posts to their community ALTER TABLE posts ADD COLUMN community_id INT; ALTER TABLE posts ADD FOREIGN KEY (community_id) REFERENCES communities(community_id);
Let's add pages to create communities and browse all available communities.
2.1 Create Community Page (create_community.php)
This lets logged-in users create new communities:
<?php require 'header.php'; if (!isset($_SESSION['uid'])) { header("Location: ./index.php?error=please_log_in"); exit(); } if (isset($_POST['submit-community'])) { require 'includes/db_conn.php'; $name = $_POST['name']; $description = $_POST['description']; $created_by = $_SESSION['uid']; if (empty($name)) { header("Location: ./create_community.php?error=empty_name"); exit(); } // Check if community name already exists $sql = "SELECT community_id FROM communities WHERE name = ?"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { header("Location: ./create_community.php?error=sqlerror"); exit(); } mysqli_stmt_bind_param($stmt, "s", $name); mysqli_stmt_execute($stmt); mysqli_stmt_store_result($stmt); if (mysqli_stmt_num_rows($stmt) > 0) { header("Location: ./create_community.php?error=community_exists"); exit(); } // Insert new community into database $sql = "INSERT INTO communities (name, description, created_by) VALUES (?, ?, ?)"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { header("Location: ./create_community.php?error=sqlerror"); exit(); } mysqli_stmt_bind_param($stmt, "ssi", $name, $description, $created_by); mysqli_stmt_execute($stmt); header("Location: ./communities.php?community=created"); exit(); } ?> <link rel="stylesheet" href="./style.css"> <div class='form-group row'> <div class="col-md-6 offset-md-3"> <h1>Create a Community</h1> <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"> <label>Community Name</label><br /> <input type="text" name="name" placeholder="e.g., Tech Talk" required><br /> <label>Description</label><br /> <textarea cols='97' rows='5' name='description' placeholder="Tell us about your community"></textarea><br /> <button type="submit" name="submit-community">Create Community</button> </form> </div> </div> <?php require 'footer.php'; ?>
2.2 Communities List Page (communities.php)
Show all communities so users can browse and access their posts:
<?php require 'header.php'; require 'includes/db_conn.php'; if (!isset($_SESSION['uid'])) { header("Location: ./index.php?error=please_log_in"); exit(); } // Fetch all communities with creator info $sql = "SELECT communities.*, users.username FROM communities INNER JOIN users ON communities.created_by = users.uid ORDER BY date_created DESC"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { header("Location: ./index.php?error=sqlerror"); exit(); } mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); ?> <link rel="stylesheet" href="./style.css"> <div class="container"> <h1>Communities</h1> <a href="./create_community.php" class="btn btn-primary mb-3">Create New Community</a> <div class="row"> <?php while ($row = mysqli_fetch_assoc($result)): ?> <div class="col-md-4 mb-4"> <div class="card"> <div class="card-body"> <h5 class="card-title"><a href="./community_posts.php?community_id=<?php echo $row['community_id']; ?>"><?php echo htmlspecialchars($row['name']); ?></a></h5> <p class="card-text"><?php echo htmlspecialchars($row['description']); ?></p> <p class="card-text"><small class="text-muted">Created by <?php echo htmlspecialchars($row['username']); ?></small></p> </div> </div> </div> <?php endwhile; ?> </div> </div> <?php require 'footer.php'; ?>
Update your newpost.php to let users select a community when creating a post:
<?php require 'header.php'; if (!isset($_SESSION['uid'])) { header("Location: ./index.php?error=please_log_in"); exit(); } // Fetch all communities for the dropdown menu require 'includes/db_conn.php'; $sql = "SELECT community_id, name FROM communities ORDER BY name ASC"; $stmt = mysqli_stmt_init($conn); mysqli_stmt_prepare($stmt, $sql); mysqli_stmt_execute($stmt); $communities = mysqli_stmt_get_result($stmt); ?> <link rel="stylesheet" href="./style.css"> <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"> <div class='form-group row'> <div class="col-md-6 offset-md-3"> <h1 id="createpost">Create a Post</h1> <label>Title</label><br /> <input type="text" name="title" placeholder="Title" required><br /> <!-- Add Community Selection Dropdown --> <label>Post to Community</label><br /> <select name="community_id" required> <option value="">Select a community</option> <?php while ($community = mysqli_fetch_assoc($communities)): ?> <option value="<?php echo $community['community_id']; ?>"><?php echo htmlspecialchars($community['name']); ?></option> <?php endwhile; ?> </select><br /> <label>Video Link</label><br> <input type='url' id='vid' name='video' placeholder="Video Link"/><br> <label>Description</label><br /> <textarea cols='97' rows='10' name='content' required></textarea><br> <button id="btnn" type="submit" name="submit-post">Post</button> </div> </div> </form> <?php if (isset($_POST['submit-post'])) { $title = $_POST['title']; $content = $_POST['content']; $video = $_POST['video']; $uid = $_SESSION['uid']; $community_id = $_POST['community_id']; $view = 1; if (empty($title) || empty($content) || empty($community_id)) { header("Location: ./newpost.php?error=emptyfield"); exit(); } // Insert post with community ID $sql = "INSERT INTO posts (uid, title, content, video, datePosted, views, community_id) VALUES (?, ?, ?, ?, now(), ?, ?);"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { header("Location: ./newpost.php?error=sqlerror"); exit(); } else { mysqli_stmt_bind_param($stmt, "issssi", $uid, $title, $content, $video, $view, $community_id); mysqli_stmt_execute($stmt); // Redirect to the community's post page after successful post header("Location: ./community_posts.php?community_id=" . $community_id . "&post=successful"); exit(); } mysqli_stmt_close($stmt); mysqli_close($conn); } require 'footer.php'; ?>
community_posts.php) This page displays all posts belonging to a single community:
<?php require 'header.php'; require 'includes/db_conn.php'; if (!isset($_SESSION['uid'])) { header("Location: ./index.php?error=please_log_in"); exit(); } $community_id = $_GET['community_id']; // Validate the community exists $sql = "SELECT name FROM communities WHERE community_id = ?"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { header("Location: ./communities.php?error=sqlerror"); exit(); } mysqli_stmt_bind_param($stmt, "i", $community_id); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); if (!$community = mysqli_fetch_assoc($result)) { header("Location: ./communities.php?error=invalid_community"); exit(); } // Fetch all posts in this community $sql = "SELECT posts.post_id, posts.title, posts.content, posts.datePosted, users.username FROM posts INNER JOIN users ON posts.uid=users.uid WHERE posts.community_id = ? ORDER BY datePosted DESC"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { header("Location: ./communities.php?error=sqlerror"); exit(); } mysqli_stmt_bind_param($stmt, "i", $community_id); mysqli_stmt_execute($stmt); $posts = mysqli_stmt_get_result($stmt); ?> <link rel="stylesheet" href="./style.css"> <div class="container"> <h1>Posts in <?php echo htmlspecialchars($community['name']); ?></h1> <a href="./newpost.php" class="btn btn-primary mb-3">Create Post in This Community</a> <a href="./communities.php" class="btn btn-secondary mb-3">Back to Communities</a> <div class="posts-list"> <?php if (mysqli_num_rows($posts) > 0): ?> <?php while ($row = mysqli_fetch_assoc($posts)): ?> <div class="card mb-3"> <div class="card-body"> <h5 class="card-title"><a href="./showpost.php?postId=<?php echo $row['post_id']; ?>"><?php echo htmlspecialchars($row['title']); ?></a></h5> <p class="card-text"><?php echo substr(htmlspecialchars($row['content']), 0, 150) . "..."; ?></p> <p class="card-text"><small class="text-muted">Posted by <?php echo htmlspecialchars($row['username']); ?> on <?php echo $row['datePosted']; ?></small></p> </div> </div> <?php endwhile; ?> <?php else: ?> <p>No posts yet! Be the first to post in this community.</p> <?php endif; ?> </div> </div> <?php require 'footer.php'; ?>
Modify your existing showpost.php to show which community the post belongs to, and add a link back to that community:
<?php require 'header.php'; require 'includes/db_conn.php'; if (!isset($_SESSION['uid'])) { header("Location: ./index.php?error=please_log_in"); exit(); } $postId = $_GET['postId']; // Increment post views $sql = "UPDATE posts SET views=views+1 WHERE post_id=?;"; $stmt = mysqli_stmt_init($conn); mysqli_stmt_prepare($stmt, $sql); mysqli_stmt_bind_param($stmt, "i", $postId); mysqli_stmt_execute($stmt); // Fetch post with community details $sql = "SELECT posts.post_id, posts.title, posts.content, posts.video, posts.datePosted, users.username, communities.name AS community_name, communities.community_id FROM posts INNER JOIN users ON posts.uid=users.uid INNER JOIN communities ON posts.community_id=communities.community_id WHERE posts.post_id=?;"; $stmt = mysqli_stmt_init($conn); if(!mysqli_stmt_prepare($stmt, $sql)) { header("Location: ./communities.php?error=sqlerror"); exit(); } else { mysqli_stmt_bind_param($stmt, "i", $postId); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); if ($row = mysqli_fetch_assoc($result)) { echo "<div class='container'>"; // Add community link echo "<p class='text-muted'>Posted in: <a href='./community_posts.php?community_id=" . $row['community_id'] . "'>" . htmlspecialchars($row['community_name']) . "</a></p>"; echo "<table class='table'>"; echo "<tr><th>Title</th><th>Posted By</th><th>Date Posted</th></tr>"; echo "<tr><td>" . htmlspecialchars($row['title']) . "</td><td>" . htmlspecialchars($row['username']) . "</td><td>" . $row['datePosted'] . "</td></tr>"; echo "</table>"; echo "<table class='table'>"; echo "<tr><th>Content</th></tr>"; echo "<tr><td>" . htmlspecialchars($row['content']) . "</td></tr>"; echo "</table>"; // Video embedding (sanitized) if (!empty($row['video'])) { echo "<div class='vidd'>"; $text = preg_replace("#.*youtube\.com/watch\?v=#" , "", $row['video']); $text = '<iframe width="1280" height="800" id="vidd" src="https://www.youtube.com/embed/' . $text . '" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>'; echo $text; echo "</div>"; } // Reply form echo "<form action='includes/replyhandler.php?postId=" . $postId . "' method='post'>"; echo "<div class='form-group text-center'>"; echo "<label>Post a Comment!</label><br />"; echo "<textarea cols='80' rows='5' id='comment' name='comment'></textarea>"; echo "</div>"; echo "<div class='form-group text-center'>"; echo "<button class='btn btn-primary' type='submit' name='submit-reply'> Add Reply</button>"; echo "</div>"; echo "</form>"; // Display comments $sql = "SELECT replies.comment, replies.datePosted, users.username FROM replies INNER JOIN users ON replies.uid=users.uid WHERE replies.post_id=? ORDER BY reply_id DESC;"; $stmt = mysqli_stmt_init($conn); if(!mysqli_stmt_prepare($stmt, $sql)) { header("Location: ./communities.php?error=sqlerror"); exit(); } else { mysqli_stmt_bind_param($stmt, "i", $postId); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); echo "<table class='table'>"; echo "<tr><th>Comment</th><th>Posted By</th><th>Date Posted</th></tr>"; while($row = mysqli_fetch_assoc($result)) { echo "<tr><td>" . htmlspecialchars($row['comment']) . "</td><td>" . htmlspecialchars($row['username']) . "</td><td>" . $row['datePosted'] . "</td></tr>"; } echo "</table>"; } echo "</div>"; } else { echo "<p> No Content</p>"; } } require 'footer.php'; ?> <link rel="stylesheet" href="./video.css">
- I added
htmlspecialchars()wherever user-generated content is displayed to prevent XSS attacks—make sure you keep this practice up! - If you want to restrict access to communities, add a
community_memberstable to track which users are part of which communities. - Consider adding moderation tools (like deleting posts/communities) for community creators or admins.
- Add error handling for




