Saving the page association in your database when new entries are created requires that you modify your query in update.inc.php, as well as a couple more checks to ensure that errors don't occur.
To save the entry information, you need to:
Make sure the page was specified before processing
Add the page to the query to be saved
Sanitize the data
Use the sanitized page information to send the user back to the created entry
In update.inc.php, modify the script to include the lines highlighted in bold:
<?php if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['submit']=='Save Entry' && !empty($_POST['page']) && !empty($_POST['title']) && !empty($_POST['entry'])) { // Include database credentials and connect to the database include_once 'db.inc.php'; $db = new PDO(DB_INFO, DB_USER, DB_PASS); // Save the entry into the database $sql = "INSERT INTO entries (page, title, entry) VALUES (?, ?, ?)"; $stmt = $db->prepare($sql); $stmt->execute( array($_POST['page'],$_POST['title'],$_POST['entry']) ); $stmt->closeCursor(); // Sanitize the page information for use in the success URL $page = htmlentities(strip_tags($_POST['page']));
// Get the ID of the entry you just saved $id_obj = $db->query("SELECT LAST_INSERT_ID()"); $id = $id_obj->fetch(); $id_obj->closeCursor(); // Send the user to the new entry header('Location: /simple_blog/?page='.$page.'&id='.$id[0]); exit; } else { header('Location: ../'), exit; } ?>
Making these changes, effectively ensures that a page association is passed to the update script; you can then insert the association using your prepared statement. Afterward, you sanitize the page information and store it in the $page variable. Finally, you send the user to the new entry by passing the page in the URL, along with the ID of the new entry.
Save update.inc.php and navigate to http://localhost/simple_blog/?page=about, then click the "Post a New Entry" link. Now create an "About the Author" entry and click "Save Entry"; this should take you to the entry saved with the "about" page association (see Figure 6-6).