In this final step, you will create the replytopost.php script, which contains code that looks similar to the script used to add a new topic. Listing 21.5 shows the code for this all-in-one form and script, which begins with the database connection on line 2. Although the script performs different tasks depending on the status of the form (whether it's being shown or submitted), both conditions require database interaction at some point. Listing 21.5. Script to Add Replies to a Topic
Line 6 checks to see whether the form is being submitted. If $_POST does not have a value, the form has not yet been submitted, and it must be shown. Before showing the form, however, you must check for that one required item; lines 811 check for the existence of a value for post_id in the GET query string. If a value in $_GET["post_id"] does not exist, the user is redirected back to the topic listing page. If you made it past the check for a value in $_GET["post_id"], lines 1419 issue a complicated-looking query that gets the values of the topic_id and topic_title fields from the forum_topics table, based on the only value that you know: the value of $_GET["post_id"]. This query both validates the existence of the post and gets information you will need later in the script. Lines 2124 act on the results of this validity test, again redirecting the user back to the topiclist.php page if the test fails. If the value of $_GET["post_id"] represents a valid post, you extract the value of topic_id and topic_title in lines 2730, again using stripslashes() to remove any escape characters. Next, the entirety of the form for adding a post is printed to the screen, and that's it for this script until the form submission button is clicked. In the form, you see that the action is $_SERVER["PHP_SELF"] on line 39, indicating that this script will be recalled into action. A hidden field in line 46 holds the information that needs to be passed along to the next iteration of the script. Moving on to line 53, this block of code is executed when the script is reloaded and $_POST contains a value. This block checks for the presence of all required fields from the form (lines 6165) and then, if they are all present, issues the query to add the post to the database (lines 6873). After the post is added to the database, the user is redirected to the showtopic.php page (lines 7980), using the appropriate query string to display the active topic. If you save this file as replytopost.php and place it in your web server document root, try it out and you may see something like Figures 21.8 and 21.9. Figure 21.8. Preparing to add a post.Figure 21.9. A post was added to the list. |