Your entry form is set to submit entered values using the POST method to a file located at inc/update.inc.php. The next step is to create the file that will accept the input from the form and save entries to the database.
First, you need to create the inc folder. You create a folder for this script because it won't be accessed directly by a browser.
|
In your simple_blog project, create the inc folder, then create a file called update.inc.php. This script will have logic that determines whether input should be saved; it will also have the ability to save entries to the entries table.
|
It is critical that you plan your script that processes form input properly; a good way to do that is to break the process into small, discrete steps:
Verify that information was submitted via the POST method
Verify that both the title and entry form fields were filled out
Connect to the database
Formulate a MySQL query to store the entry data
Sanitize the input and store it in the entries table
Obtain the unique ID for the newly created entry
Send the user to the newly created entry
You can combine the first three steps into one conditional statement. All conditions are required, so you can use the && operator to require that all conditions are true. The conditional statement looks like this:
<?php if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['submit']=='Save Entry' && !empty($_POST['title']) && !empty($_POST['entry'])) { // Continue processing information . . . } // If both conditions aren't met, sends the user back to the main page else { header('Location: ../admin.php'), exit; } ?>
You use the $_SERVER superglobal to determine whether the script was accessed using the POST method. Making this check helps you ensure that the page wasn't accessed by mistake. You use the $_POST superglobal to access the value of the button pressed to submit the form. If the pressed button wasn't the "Save Entry" button, the form isn't submitted. This makes it possible for the Cancel button to send the user back to the main page without saving any of the input from the form. Finally, you use the $_POST superglobal to verify that the user filled out the title and entry fields of the form; performing this check helps you ensure that you don't store any incomplete entries in the database.
If any of these conditions isn't met, the user is sent back to the main page, and your script performs no further processing. This means that any information submitted won't be saved to the database.
If all conditions were met, the script can proceed to Step 4, where you save the information to your database. You need to open a connection to the database before you can save to it; you open the connection using PHP Data Objects (PDO).
It's a good habit to keep database credentials and other site-wide information separate from the rest of your scripts. The reason: This allows you to change an entire project's configuration quickly and easily by altering a single file.
You might wonder why skipping this step could matter. Imagine that you build a project that has dozens of scripts, all of which need to contact the database for some reason or another. Now imagine that the database is moved to a new server, and the login credentials need to be updated. If you did not keep site-wide information separate from the rest of your scripts in this scenario, you would be required to open every single file in your project to swap in the new login information—this would be a tedious and potentially time-consuming task.
If, however, you store all the login credentials and other scripts that access the database in one file, you're able to move the site to a new database by altering a single file.
You store your database credentials in a file you create and store in the inc folder called db.inc.php (full path: /xampp/htdocs/simple_blog/inc/db.inc.php). You can define the credentials as constants with the following code:
<?php define('DB_INFO', 'mysql:host=localhost;dbname=simple_blog'), define('DB_USER', 'root'), define('DB_PASS', ''), ?>
All that remains is to include db.inc.php in any file that needs database access, and you have access to your credentials.
Next, add the bolded lines to update.inc.php to include your credentials and open a connection to the database:
<?php if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['submit']=='Save Entry') { // Include database credentials and connect to the database include_once 'db.inc.php'; $db = new PDO(DB_INFO, DB_USER, DB_PASS); // Continue processing data... } // If both conditions aren't met, send the user back to the main page else { header('Location: ../admin.php'), exit; } ?>
When you're sure that all the necessary conditions have been met and a connection to the database is open, you're ready to proceed with Steps 5 and 6: formulating a MySQL query to store the entry data and then sanitizing the input and storing it in the entries table. To accomplish these tasks, you need to create a prepared statement. Begin by creating a query template, which you use to save the title and entry fields entered to the title and entry columns in the entries table. The query looks like this:
INSERT INTO entries (title, entry) VALUES (?, ?)
You store this query in a variable that you pass to PDO's prepare() method. With your query prepared, you can execute the statement using the supplied form information, confident that the input is being escaped properly.
Add the code in bold to update.inc.php:
<?php if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['submit']=='Save 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 (title, entry) VALUES (?, ?)"; $stmt = $db->prepare($sql); $stmt->execute(array($title, $entry)); $stmt->closeCursor(); // Continue processing data... } // If both conditions aren't met, sends the user back to the main page else { header('Location: ../admin.php'), exit; } ?>
The execute() method saves the information into the entries table. Finally, call the closeCursor() method to end the query.
You've saved your new entry successfully; the final pair of steps is to obtain the unique ID of the new entry and enable the user to view his new entry.
To accomplish this, you need the ID generated for the entry you just saved. Fortunately, MySQL provides a built-in function for tackling the first part of this; you can use the LAST_INSERT_ID() function to structure a query that retrieves the unique ID of the new entry:
SELECT LAST_INSERT_ID()
When you access the results of the query using the fetch() method, you're given an array in which the first index (0) contains the ID of the last entry inserted into the database.
Once you have the ID, you want to send the user to the publicly displayed page that contains his entry, which you call index.php. To do this, you need to insert the id of the entry you want to display in a URL:
http://localhost/simple_blog/index.php?id=1
You can shorten the URL like this:
http://localhost/simple_blog/?id=1
Now add the following code to update.inc.php to retrieve the entry's ID and direct the user to the entry's public display:
<?php if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['submit']=='Save 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 (title, entry) VALUES (?, ?)"; $stmt = $db->prepare($sql); $stmt->execute(array($_POST['title'], $_POST['entry'])); $stmt->closeCursor(); // Get the ID of the entry we 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: ../admin.php?id='.$id[0]); exit; } // If both conditions aren't met, sends the user back to the main page else { header('Location: ../admin.php'), exit; } ?>
NOTE
You haven't created index.php yet, so this code redirects to admin.php. You'll change this when you create index.php in the next step.
No matter how the script is accessed, the user will receive a resolution: either the script executes successfully and the user is shown her new entry, or the script takes her back out to the main display and nothing is saved.
You can test the new system by adding three dummy entries to the system:
Title: First Entry; Entry: This is some text.
Title: Second Entry; Entry: More text and a <a href="#">link</a>.
Title: Third Entry; Entry: A third entry in the database.
These entries will give you some test data to work with when you move on to the next step, which is to build the script that retrieves entries from the database and displays them.