PHP/MySQLi Creating a Forum - Part 18 - Related Threads

PHP/MySQLi Creating a Forum - Part 17 - User List Introduction: This tutorial will be continuing my series of creating a forum in PHP/MySQLi/HTML. In this part I will be covering related threads. 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 all the previous parts of this tutorial series which can all be found on my profile tracking page. Just Information: This is not something which I had even considered covering, until today. Theory: As you know, when we create a new thread, we enter some tags. So; these tags are related to the thread, right? In that case, we can simply use those tags to find related threads to the current one. Editing threadPage.php: First we want to get the tags for the current thread, remove the spaces (as they should be separated by a comma as mentioned on the create thread form), then split the value by a comma so we get an array of tags...
  1. //Tags for related threads;
  2. $tagLine = $info['tags'];
  3. $tagLineNoSpaces = str_replace(" ", "", $tagLine);
  4. $tags = explode(",", $tagLineNoSpaces);
  5. $foundRelatedArticles = 0;
  6. $relatedArticleIDs = array();
  7. $relatedArticleTitles = array();
  8. $tagQ = mysqli_query($con, "SELECT * FROM `threads`");
  9. $tInfo = mysqli_fetch_array($tagQ);
  10. for ($t=0;$t<mysqli_num_rows($tagQ);$t++) {
  11. if ($foundRelatedArticles <= 2) {
  12. $ttQ = mysqli_query($con, "SELECT * FROM `threads` WHERE `id`='$t'");
  13. $ttInfo = mysqli_fetch_array($ttQ);
  14. $tTagLine = $ttInfo['tags'];
  15. $tTagLineNoSpaces = str_replace(" ", "", $tTagLine);
  16. $tTags = explode(",", $tTagLineNoSpaces);
  17. $hasAdded = false;
  18. for ($i=0;$i<count($tags);$i++) {
  19. if (!$hasAdded) {
  20. for($tt = 0;$tt < count($tTags);$tt++) {
  21. if ($tags[$i] == $tTags[$tt] && $ttInfo['id'] != $id) {
  22. $foundRelatedArticles++;
  23. array_push($relatedArticleIDs, $ttInfo['id']);
  24. array_push($relatedArticleTitles, $ttInfo['title']);
  25. $hasAdded = true;
  26. }
  27. }
  28. }
  29. }
  30. }
  31. }
As you can see, we get all the separated tags (split by a comma) in our new tags array variable. Next we create three new variables to store how many related threads we've found, their ids and titles. Next, we get and count the total amount of threads there are, and begin to iterate through them all from start to finish. Before we do anything with each one, we check to see if we have 3 or less threads found that are related to the current thread... if we've already found 3 then there's no point in processing them. If we need more related articles, we get the row by selecting it through the found id, then we get the information, get the tags, remove the spaces and split it by all the commas again (just like our current/displaying threads tags), now we have these in our tTags array variable. Next we create a variable to see if the thread has been added (the default is false), this is because we now process each tag within the processing thread, if multiple tags match more than one tag in the displaying thread, it would get added more than once. But because we set our boolean variable to true (hasAdded), we make sure it only gets added once. So now we have all the information, the only parts left are the displaying ones. I am going to use my overused method of using a variable table in php, we need to create this outside of any blocks in our PHP, above the related code (above this paragraph)...
  1. $related = '<table><tbody><tr>';
Then, under the ending to our main bulk of just added code, we add the following code which will go through each related article within our arrays and add them as a new column* within our table, I have used a column because if/when I style my forum, I want it to be three related articles inline with each other at the bottom of the page. You can use and to surround the information if you want to use new rows for each related thread/article. As you can see we also give each one a link to the same threadPage.php page but with it's own tid so it displays the correct information. We surround the relatead thread's title with the link...
  1. for($fi=0;$fi<$foundRelatedArticles;$fi++) {
  2. $related .= '<td><a href="threadPage.php?tid='.$relatedArticleIDs[$fi].'">'.$relatedArticleTitles[$fi].'</a></td>';
  3. }
  4. $related .= '</tr></tbody></table>';
  5. //End tags
Finally we need to actually display it in the browsers HTML...
  1. echo $related;
Please forgive any mistakes I have made (if any) within the post, I have been looking at the monitor for a long time! The finished (edited) threadPage.php is attached. threadPage.php Source Code Before Editing! Here is my source code for threadPage.php (with required login etc.) before this tutorials edits...
  1. <?php
  2. if (!isSet($_SESSION['username'])) {
  3. header("Location:login.php");
  4. exit();
  5. }
  6. $con = mysqli_connect('localhost', 'root', '', 'forumTutorial') or die(mysql_error());
  7. $username;
  8. if (isSet($_SESSION['username']))
  9. $username = $_SESSION['username'];
  10. if (isSet($_POST['replySent']) && isSet($_POST['cont']) && $_POST['cont'] != '' && isSet($_GET['tid']) && $_GET['tid'] != '') {
  11. $cont = $_POST['cont'];
  12. $thread = $_GET['tid'];
  13. $user = $_SESSION['username'];
  14. $q = mysqli_query($con, "INSERT INTO `replies` VALUES ('', '$thread', '$cont', '$user')");
  15. $qu = mysqli_query($con, "SELECT * FROM `subscriptions` WHERE `threadID`='$thread'");
  16. if (mysqli_num_rows($qu) > 0) {
  17. $msg = 'A new reply has been submitted to a thread you have subscribed to. '.$user.' had this to say:<br/>'.$cont;
  18. while ($row = mysqli_fetch_array($qu)) {
  19. mail($row['email'], 'New Reply', $msg);
  20. }
  21. }
  22. if ($q) {
  23. echo 'Reply submitted.';
  24. }else
  25. echo 'Failed inserting reply.';
  26. }
  27. $replies = '';
  28. $id;
  29. if (isSet($_GET['tid']) && $_GET['tid'] != '') {
  30. $id = $_GET['tid'];
  31. $query = mysqli_query($con, "SELECT * FROM `threads` WHERE `id`='$id'");
  32. if (mysqli_num_rows($query) > 0) {
  33. $info = mysqli_fetch_array($query);
  34. $qu = mysqli_query($con, "SELECT * FROM `replies` WHERE `threadID`='$id'");
  35. if (mysqli_num_rows($qu) > 0) {
  36. $replies = '<table><tbody>';
  37. while ($row = mysqli_fetch_array($qu)) {
  38. $replies .= '<tr><td>'.$row["content"].'</td><td>'.$row["author"].'</td></tr>';
  39. }
  40. $replies .= '</tbody></table>';
  41. }
  42. $title = $info['title'];
  43. $content = $info['content'];
  44. $author = $info['author'];
  45. }else{
  46. echo 'fake tid.';
  47. $dontDisplay = true;
  48. }
  49. }else{
  50. echo 'fail tid.';
  51. $dontDisplay = true;
  52. }
  53.  
  54. if (!isSet($dontDisplay)) {
  55. echo "
  56. <html>
  57. <head></head>
  58. <body>
  59. <div>
  60. <h1>Rate Thread:</h1>
  61. <a href='rateThread.php?tid=$id]&rating=1'><p>1 Star</p></a>
  62. <a href='rateThread.php?tid=$id&rating=2'><p>2 Stars</p></a>
  63. <a href='rateThread.php?tid=$id&rating=3'><p>3 Stars</p></a>
  64. <a href='rateThread.php?tid=$id&rating=4'><p>4 Stars</p></a>
  65. <a href='rateThread.php?tid=$id&rating=5'><p>5 Stars</p></a>
  66. </div>
  67. <h3>";
  68. $qq = mysqli_query($con, "SELECT * FROM `threads` WHERE `id`='$id'");
  69. if (mysqli_num_rows($qq) > 0) {
  70. $info = mysqli_fetch_array($qq);
  71. $all = $info['rating'];
  72. $total = $info['totalRatings'];
  73. if ($all == 0 || $all == null || $total == 0 || $total == null) {
  74. echo 'No ratings have yet been given for this thread.';
  75. }else {
  76. $average = $all / $total;
  77. echo 'Average Rating: '.$average;
  78. }
  79. }
  80. echo "</h3>
  81. <h1>$title</h1>
  82. <p>$content</p>
  83. <br/>
  84. <p>By $author</p>
  85. <br/>
  86. <h1>Leave a Reply:</h1>
  87. <form action="; echo 'threadPage.php?tid='.$_GET['tid']; echo " method='POST'>
  88. <table>
  89. <tbody>
  90. <tr>
  91. <td>Name: </td><td>$username</td>
  92. </tr>
  93. <tr>
  94. <td>Message: </td><td><input type='text' name='cont' /></td>
  95. </tr>
  96. <tr>
  97. <td></td><td><input type='submit' value='Post Reply' name='replySent' /></td>
  98. </tr>
  99. </tbody>
  100. </table>
  101. </form>
  102. <br/>";
  103. if (isSet($_SESSION['username'])) {
  104. echo '<form action="subPage.php?tid='.$_GET['tid'].'" method="POST"><h1>Subscribe to Thread:</h1>Email: <input type="text" name="email" /><br/><input type="submit" name="subscribe" value="Subscribe" />';
  105. }
  106. echo "
  107. <br/>
  108. $replies
  109. </body>
  110. </html>
  111. ";
  112. }
  113. ?>

Add new comment