Jump to content
Larry Ullman's Book Forums

Review And Persue Chapter 9 Edit_Page.php - Need Help


Recommended Posts

Here is my code which I've written to make the 'edit_page', but am unable to update the database.

 

Please, anyone, take a look and help me out by pointing out my mistakes and how to rectify them. Also some pointers to improve code/coding skills would be really appreciated.

 

Thanks in advance.

<?php
# Script 9.17 - edit_page.php
// This page both displays and handles the "Edit" page.

require ('includes/utilities.inc.php');

try
{
    // Validate page Id
    if
    (
        !isset($_GET['id']) ||
        !filter_var($_GET['id'], FILTER_VALIDATE_INT, array('min_range' => 1))
    )
    {
        throw new Exception('e1 An invalid page Id was provided to this page.');
    }
    $_SESSION['id'] = $_GET['id'];
    
    // Fetch content from the database:
    $q = 'SELECT id, title, content, creatorId
         FROM pages
         WHERE id=:pageId
         LIMIT 1';
    $stmt = $pdo->prepare($q);
    $r = $stmt->execute(array(':pageId' => $_GET['id']));

    if ($r)
    {
        $stmt->setFetchMode(PDO::FETCH_CLASS, 'Page');
        $page = $stmt->fetch();
    }
    if (!$page)
    {
        throw new Exception ('Failed to retrieve data.');
    }
}
// Catch generic Exceptions:
catch (Exception $e)
{
    $pageTitle = 'Error';
    include ('includes/header.inc.php');
    include ('views/error.html');
    include ('includes/footer.inc.php');
}

// Create the form:
require ('HTML/QuickForm2.php');

$form = new HTML_QuickForm2('editPageForm');

// Add the title field:
$title = $form->addElement('text', 'title');
$title->setLabel('Page Title');
$title->addFilter('strip_tags');
$title->addRule('required', 'Please enter page title');
$title->setValue($page->getTitle());
$title->getValue();

// Add the content field:
$content = $form->addElement('textarea', 'content');
$content->setLabel('Page Content');
$content->addFilter('trim');
$content->addRule('required', 'Please enter the page cotent');
$content->setValue($page->getContent());
$content->getValue();

// Add the submit button:
$submit = $form->addElement('submit', 'submit',
                            array('value' => 'Update This Page'));

// Check for a form submission:
// Handle the form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    // Validate the form data:
    if ($form->validate())
    {
        // Update the database:
        $q = 'UPDATE pages
              SET title=:title, content=:content dateUpdated=:date
              WHERE id=:pageId AND creatorId=:creatorId
              LIMIT 1';
        $stmt = $pdo->prepare($q);
        $r = $stmt->execute
             (
                 array
                 (
                     ':title'        => $title->getValue(),
                     ':content'      => $content->getValue(),
                     ':date'         => NOW(),
                     ':pageId'       => $_GET['id'],
                     ':creatorId'    => $user->getId()
                 )
             );
        
        // Freeze the form upon success:
        if ($r)
        {
            $form->toggleFrozen(true);
            $form->removeChild($submit);
        }
    }
}
$pageTitle = 'Edit Page';
include ('includes/header.inc.php');
include ('views/edit_page.html');
include ('includes/footer.inc.php');

?>

You'll need to store the ID value ($_GET['id'] when the page is first loaded) in a hidden form input (or a session) so that the update query has access to it.

This is from post http://larryullman.com/forums/index.php?/topic/1758-chapter-9-exercises/?hl=%2Bedit+%2Bpage.

Is this how I should do it?

$_SESSION['id'] = $_GET['id'];

I get only error when I click the submit button.

Edited by alex_r
Link to comment
Share on other sites

  • 2 weeks later...

I get this error message: "e1 An invalid page Id was provided to this page." which is in this code (above)

throw new Exception('e1 An invalid page Id was provided to this page.');

under Validate page Id block.

Link to comment
Share on other sites

I've got it working now . (After a few changes) However I've some other question now:

 

1. Is doing something like this OK/good practice? Specially the elseif block (for SessionID) which does nothing if validated?

    if (isset($_GET['id']))
    {
        if (filter_var($_GET['id'], FILTER_VALIDATE_INT, array('min_range' => 1)))
        {
            $_SESSION['id'] = $_GET['id'];
        }    
    }
    elseif
    (
        isset($_SESSION['id']) ||
        filter_var($_SESSION['id'], FILTER_VALIDATE_INT, array('min_range' => 1))
    )
    {
        ;
    }
    else
    {
        throw new Exception("An Invalid Page Id was provided");
    }

2. Will it be Ok/good practice to store $page object is session (through page.php) so that the script can call the User::canEditPage() method which requires an argument of type Page (and since the method needs to call the creatorId [$page->getCreatorId()] to do something equivalent to the scrippet below from add_page.php?

// Redirect if the user doesn't have permission:
if (!$user->canCreatePage())
{
    header ("Location:index.php");
    exit;
}
Edited by alex_r
Link to comment
Share on other sites

Glad you've got it working! I would never have a nothing clause like you've written there. If the code literally does nothing, it's not necessary. You could create a local variable, say, $id, in the else and elseif and then throw an exception if $id isn't set (in a separate conditional). 

 

It's totally fine to store objects in the session so long as every page that uses that object has access to the class definition! 

Link to comment
Share on other sites

 Share

×
×
  • Create New...