Ever wanted to build a threaded news system? If so, this article is for you. In it, the Free2Code team show us how to do just that using PHP and MySQL...
The news table is pretty simple. We just store a unique ID for each post along with the name of the person who posted the announcement, the title of the announcement and the announcement itself.
The comments table stores three extra values -- the news_idb, the rel_id and the replies:
news_id: We'll use this value to show which news post a comment belongs to. For example, if a news post has the ID of 1, then any comments with a news_id of 1 will be associated with the news post ID that matches its news_id value.
rel_id: We will use this column to show the parent comment that a “child comment” (remember we’re working with threads) belongs to. For example, if a comment is intended to be a reply to a comment with the ID of 3, then the new comment created will have a rel_id of 3.
replies: We will use this to track how many replies a comment has had.
db_connect.php Here's the database connection script:
// connect to database $db = DB::connect($datasource);
// if errors die and display error if(DB::isError($db_object)) { die($db_object->getDebugInfo()); }
// fetch items from the db as objects $db->setFetchMode(DB_FETCHMODE_OBJECT);
Adding News Announcements (add.php) Now we need to create the script that will allow news announcements to be made:
<?php
// we need database operations require('db_connect.php'); ?> <html> <head> <title>add news</title> </head> <body> <h2>Add A News Accouncement</h2> <?php
// if form has been submitted if(isset($_POST['submit'])) { // check they filled everything in. if(!$_POST['author'] | !$_POST['title'] | !$_POST['announcement']) { die('Please fill in all the fields.'); }
// get rid of HTML or PHP tags $_POST['author'] = htmlspecialchars($_POST['author']); $_POST['title'] = htmlspecialchars($_POST['title']); $_POST['announcement'] = htmlspecialchars($_POST['announcement']);
// convert text new lines to HTML new lines. $_POST['announcement'] = str_replace("\ ", '<br>', $_POST['announcement']);
// insert into database $insert = $db->query("INSERT INTO news (author, title, announcement) VALUES ('".addslashes($_POST['author'])."', '".addslashes($_POST['title'])."', '".addslashes($_POST['announcement'])."')"); echo '<p>Cheers '.$_POST['author'].', your announcement has been added, click <a href="/index.php">here</a> to view it.</p>'; }