PHP/MySQLi Creating a Forum - Part 10 - Latest Threads

PHP/MySQLi Creating a Forum - Part 9 - Tags #2 Introduction: This tutorial will be continuing my series of creating a forum in PHP/MySQLi/HTML. In this tenth part,I shall be covering a simple script to show the three latest threads to be created. Obviously, this would be good to go on the home page; for this example I am just going to add it on to the bottom of our forumTutorial.php. Pre-creation: First you will need a host for your PHP, either a web host or localhost is fine but you will need PHP and MySQL(i) capabilities. Also, this will not be covering creating users, or styling the pages. For the purpose of using the logged in users username, we will be using $_SESSION['username']; from my login script, you can find that tutorial on my profile page. Obviously you will also need to go through the first, second, third, fourth, fifth, sixth, seventh, eight and ninth parts of this tutorial series which can all be found on my profile tracking page. Structure: To do this we are going to retrieve all the rows within the `threads` table from our database up to three, going in descending order by id. So basically, we are going to end up with the final three entries (newest) in our assortment of threads to show. HTML: Most of this will be done in the PHP part, but for my page I am just going to add a line break and the start and end of the table to keep the information in order...
  1. <br/>
  2. <table>
  3. <tbody>
  4. </tbody>
  5. </table>
When we have done the PHP part, we will be storing all of the information in a news variable, so let's output this within the table...
  1. <?php echo $news; ?>
Code: Here is the PHP code, as stated in the Structure section of this page...
  1. $news = '';
  2. $nq = mysqli_query($con, "SELECT * FROM (SELECT * FROM `threads` ORDER BY `id` DESC LIMIT 3) t ORDER BY `id` ASC");
  3. if (mysqli_num_rows($nq) > 0) {
  4. while ($row = mysqli_fetch_array($nq)) {
  5. $news .= '<tr><td><a href="threadPage.php?tid='.$row["id"].'">'.$row["title"].'</td><td>'.$row["content"].'</td></tr>';
  6. }
  7. }

Add new comment