6.2. Modify Your Functions to Accept Page Parameters

Now that your entries have a page associated with them, you can start using the page as a filter to retrieve only the data that matches your current page. This is really similar to the way you used the id column to filter your query to only return one entry. By using the page, you filter the query to only return entries for one page.

6.2.1. Accepting Page Information in the URL

First—and this is very important—you need to somehow pass a page variable to your script. You do this in the same way that you previously passed an entry ID to the script, using the URL and the $_GET superglobal.

For example, you navigate to the following address to look at the blog page:

http://localhost/simple_blog/?page=blog

Navigating to an entry within the blog requires that you use a URL similar to the following:

http://localhost/simple_blog/?page=blog&id=2

To use the preceding URL format, you need to modify index.php to use the page variable passed in the URL, then modify functions.inc.php to accept the page variable and use it in your database query.

Begin by opening index.php (full path: /xampp/htdocs/simple_blog/index.php) and adding the code in bold to the top of the script:

<?php
    /*
     * Include the necessary files
     */
    include_once 'inc/functions.inc.php';
    include_once 'inc/db.inc.php';

    // Open a database connection
    $db = new PDO(DB_INFO, DB_USER, DB_PASS);

/*
     * Figure out what page is being requested (default is blog)
     * Perform basic sanitization on the variable as well
     */
    if(isset($_GET['page']))
    {
        $page = htmlentities(strip_tags($_GET['page']));
    }
    else
    {
        $page = 'blog';
    }

    // Determine if an entry ID was passed in the URL
    $id = (isset($_GET['id'])) ? (int) $_GET['id'] : NULL;

    // Load the entries
    $e = retrieveEntries($db, $page, $id);

    // Get the fulldisp flag and remove it from the array
    $fulldisp = array_pop($e);

    // Sanitize the entry data
    $e = sanitizeData($e);
?>

Here you add a line that collects the page variable from the $_GET superglobal array, then assigns its value (or a default value, which you've set to "blog") to a variable called $page.

Next, you add the $page variable as an argument in your call to retrieveEntries($db, $page, $id); so that you can use the information in retrieving entry data.

For now, you're finished in index.php. Next, you need to modify your retrieveEntries() function.

6.2.2. Using the Page Information to Filter Entries

The first thing you need to do is to alter retrieveEntries() to accept the $page parameter you've just added. Open functions.inc.php and alter the function definition to read as follows:

function retrieveEntries($db, $page, $url=NULL)
{

The page is being sent to your entry retrieval function, so you can use the information to filter your query and return only results relevant to the page being viewed. You accomplish this using a WHERE clause.

Originally, your query for retrieving entries when no entry ID was supplied looked like this:

SELECT id, title, entry
FROM entries
ORDER BY created DESC

Adding the WHERE clause means you can no longer simply execute the query because you're now relying on user-supplied data, which is potentially dangerous. To keep your script secure, you need to use a prepared statement. Your query uses a placeholder for the page variable and looks something like this:

SELECT id, page, title, entry
FROM entries
WHERE page=?
ORDER BY created DESC

Now you can retrieve only the entries that correspond to the page being viewed. The next step is to update your query in functions.inc.php (full path: /xampp/htdocs/simple_blog/inc/functions.inc.php). This snippet starts at line 25 in the file; add the changes highlighted in bold:

/*
 * If no entry ID was supplied, load all entry titles for the page
 */
else
{
    $sql = "SELECT id, page, title, entry
            FROM entries
            WHERE page=?
            ORDER BY created DESC";
    $stmt = $db->prepare($sql);
    $stmt->execute(array($page));

    $e = NULL; // Declare the variable to avoid errors

In this snippet, you create a prepared statement out of the query you wrote previously, then execute the statement using the $page variable you passed to retrieveEntries() from index.php.

This code also adds a line declaring the $e variable as NULL. This part serves as a precautionary measure against empty result sets, which would otherwise result in an error notice if no entries exist for the specified page.

It's a good habit to get into to always declare a variable as NULL if there's the potential for a query or loop to come back empty. This means any variable defined in a conditional statement or used to store the result of a database query should contain a NULL value before the query or loop is executed.


You changed the method you use to execute the query, so now you need to modify the way you store the result set. Add the following code in bold where indicated in functions.inc.php, immediately beneath the script you just altered, starting at line 39:

// Loop through returned results and store as an array
    while($row = $stmt->fetch()) {
        $e[] = $row;
    }

Once this code is in place, each result array is stored as an array element in $e; this means that your script will now work. Save functions.inc.php and navigate to http://localhost/simple_blog/?page=blog in a browser. At this point, you should see the previews of the blog entry (see Figure 6-1).

Figure 6.1. The blog previews page loaded with URL variables

The blog is the default page, so previews will also load without the page variable. To see the power of what you've just built, navigate to a page that doesn't exist yet: your "About the Author" page. Navigate to http://localhost/simple_blog/?page=about in a browser, and you should see your default "No Entries" message (see Figure 6-2).

Figure 6.2. The "About the Author" page with no entries supplied

Here you face with a slight problem: you have a "Back to Latest Entries" link on your "About the Author" page. This could prove misleading because it might give your users the impression that there are more entries about the author.

Additionally, the "Post a New Entry" link appears on this page. You want only one entry to appear on the "About the Author" page, so you don't want this link to appear here.

To correct this, you must modify index.php with a conditional statement that displays the "Back to Latest Entries" and "Post a New Entry" links only on the "Blog" page. Accomplish this by opening index.php and adding the code in bold to the body of the document:

<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <meta http-equiv="Content-Type"
        content="text/html;charset=utf-8" />
    <link rel="stylesheet" href="css/default.css" type="text/css" />
    <title> Simple Blog </title>
</head>

<body>

    <h1> Simple Blog Application </h1>

    <div id="entries">

<?php

// If the full display flag is set, show the entry
if($fulldisp==1)
{

?>

        <h2> <?php echo $e['title'] ?> </h2>
        <p> <?php echo $e['entry'] ?> </p>
        <?php if($page=='blog'): ?>
        <p class="backlink">
            <a href="./">Back to Latest Entries</a>
        </p>
        <?php endif; ?>

<?php

} // End the if statement

// If the full display flag is 0, format linked entry titles
else
{
    // Loop through each entry
    foreach($e as $entry) {

?>

        <p>
            <a href="?id=<?php echo $entry['id'] ?>">
                <?php echo $entry['title'] ?>

            </a>
        </p>

<?php

    } // End the foreach loop
} // End the else

?>

<p class="backlink">
        <?php if($page=='blog'): ?>
            <a href="/simple_blog/admin/<?php echo $page ?>">
                Post a New Entry
            </a>
        <?php endif; ?>
        </p>

    </div>

</body>

</html>

Now you don't see the potentially misleading links when you load http://localhost/simple_blog/?page=about (see Figure 6-3).

Figure 6.3. The "About the Author" page without potentially misleading links

The next step is to create an entry for the "About the Author" page. However, you need to update your admin.php script before you can create this entry.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.181.57