PHP/MySQLi Creating a Forum - Part 11 - User Page - Messages and User Created Threads
Introduction:
This tutorial will be continuing my series of creating a forum in PHP/MySQLi/HTML. In this fourteenth part, I will go through listing your messages.
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, ninth, tenth, eleventh, twelfth and thirteenth parts of this tutorial series which can all be found on my profile tracking page.
Account Page:
I am going to create a new page for this named 'accountPage.php' which is where we are going to allow the user to change their password in the future, as well as view all of their posted threads and received messages.
PHP:
Since this is a new page, we will want to continue our session (carry over their username within our session username variable to see if they're logged in), as well as connect to our database.
Now we are going to list all of their posted threads and received messages, which are almost the exact same code. First we want to create two new variables which will hold our HTML tables full of the information relevant to each of them...
<?php
$threads = '<table><tbody>';
$messages = '<table><tbody>';
?>
Now we want to run a query to select all the rows from our messages table which have the 'to' field as the logged in users username, then we want to iterate through them all and append each one to the messages table/variable...
$user = $_SESSION['username'];
$q = mysqli_query($con, "SELECT * FROM `messages` WHERE `to`='$user'");
$messages .= '<tr><td>'.$row["message"].'</td><td>From: </td><td>'.$row["from"].'</td></tr>';
}
}
Next we want to do the same but with the threads...
$q2 = mysqli_query($con, "SELECT * FROM `threads` WHERE `author`='$user'");
$threads .= '<tr><td><a href="threadPage.php?tid='.$row["id"].'">'.$row["title"].'</td></tr>';
}
}
Last but not least we want to finish off the table variables...
$messages .= '</tbody></table>';
$threads .= '</tbody></table>';
Displaying The Information:
Finally we want to display all the gathered information from our messages and threads tables...
<html>
<head></head>
<body>
<h1>My Threads:</h1>
<?php echo $threads; ?>
<br/>
<h1>My Messages:</h1>
<?php echo $messages; ?>
</body>
</html>