Forum Member Posts
This lesson is part of an ongoing Foruml tutorial. The first part is here: Build your own Forum, along with all the files you need. The previous lesson is here.
The next thing we need to do is find out which member posted the original thread. The code in the pageThread.php script that does this is as follows:
for ($i = 0; $i < $cnt; ++$i) {
$memb = $postData[$i]['memberID'];
$memSQL = "SELECT * from members WHERE memberID = '$memb'";
$result2 = mysql_query($memSQL);
if ($result2) {
$db_field = mysql_fetch_assoc($result2);
$memName = $db_field['username'];
$postData[$i]['member'] = $memName;
}
}
The for loop uses the same variable that we set up to count the number of positions in the 2D array. We're looping round each position in the 2D array and grabbing the memberID. The line that does that is this:
$memb = $postData[$i]['memberID'];
When we set up the 2D arrray, one of the values that was returned from the table was the memberID. We're storing this in a variable called $memb.
The next line is this:
$memSQL = "SELECT * from members WHERE memberID = '$memb'";
We're setting up some SQL here. Because we set up our database with a memberID in three of the tables, we can select all the records where the memberIDs match. Again, this shows you the benefits of planning your database before you start!
The next few lines are these:
$result2 = mysql_query($memSQL);
if ($result2) {
$db_field = mysql_fetch_assoc($result2);
$memName = $db_field['username'];
$postData[$i]['member'] = $memName;
}
First, we run the SQL:
$result2 = mysql_query($memSQL);
Next, we have an if statement testing to see if the variable called $result2 is true. If it is, the next few lines are executed. (We should really have an else part here, as well. This should say what happens if $result2 is false.)
The first line inside of the if statement is this:
$db_field = mysql_fetch_assoc($result2);
This brings back the result as an array. The array will return all the columns and the data from the table row. This is then placed into the variable called $db_field.
The only thing we need is the username. So the line is this:
$memName = $db_field['username'];
We're placing the username in a variable called $memName. This is then added to the 2D array:
$postData[$i]['member'] = $memName;
We now have a new key and value in our 2D array - member. This holds the member's username. If you wanted to display other information about the member, you would do it here. Get the email address, for example, or that Avatar we didn't set up! You'd do it like this:
$email = $db_field['username'];
$postData[$i]['emailAddress'] = $email;
In other words, grab the column name from the table, and add a new key to the
2D array.
In the next part, you'll see how to print out all the values we've grabbed from the pageThread.php page.