Jump to content
Larry Ullman's Book Forums

Ch10, My Solution To Pursue Exercises With Questions


Recommended Posts

Larry and all,

If you could take a look at my solution and correct me if any mistake, I would be much appreciated.

 

1. Change the delete_user.php and edit_user.php pages so that they both display the user being affected in the browser window’s title bar.

 

Made the change in Header.html:

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title><?php echo $page_title . '(' . $_GET['ln'] . ' ' . $_GET['fn'] . ')'; ?></title>
    <link rel="stylesheet" href="includes/style.css" type="text/css">
</head>

 

Then both delete and edit scripts can reflect user's name in browser windows's title bar. One question is for the $_POST case(the form is submitted, and there's no $GET[] value), should we handle it also? If so then I guess I need to write a conditional here in Header.html.

 

 

2. Modify edit_user.php so that you can also change a user’s password.
3. If you’re up for a challenge, modify edit_user.php so that the form elements’ values come from $_POST, if set, and the database if not.

 

<?php # Script 10.3 - edit_user.php - PURSUE
// This page is for editing a user record.
// This page is accessed through view_users.php.

$page_title = 'Edit a User';
include ('includes/header.html');
echo '<h1>Edit a User</h1>';

// Check for a valid user ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_users.php
    $id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.
    $id = $_POST['id'];
} else { // No valid ID, kill the script.
    echo '<p class="error">This page has been accessed in error.</p>';
    include ('includes/footer.html');
    exit();
}

require ('./mysqli_connect.php');

// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $errors = array();
    
    // Check for a first name:
    if (empty($_POST['first_name'])) {
        $errors[] = 'You forgot to enter your first name.';
    } else {
        $fn = mysqli_real_escape_string($dbc, trim($_POST['first_name']));
    }
    
    // Check for a last name:
    if (empty($_POST['last_name'])) {
        $errors[] = 'You forgot to enter your last name.';
    } else {
        $ln = mysqli_real_escape_string($dbc, trim($_POST['last_name']));
    }

    // Check for an email address:
    if (empty($_POST['email'])) {
        $errors[] = 'You forgot to enter your email address.';
    } else {
        $e = mysqli_real_escape_string($dbc, trim($_POST['email']));
    }
    
    // PURSUE 2 - Check for a NEW password(updated) and match against the confirmed password:
        //If these values are submitted, update the password in the database as well. If these inputs are left blank, do not update the password in the database.(do not put an error message in $errors[] & use the original $q)

    if (!empty($_POST['pass1'])) {
        if ($_POST['pass1'] != $_POST['pass2']) {
            $errors[] = 'Your new password did not match the confirmed password.';
        } else {
            $np = mysqli_real_escape_string($dbc, trim($_POST['pass1']));
        }
    } // if pass1 is empty, then do nothing here, delete the original else statement. But nend to add judge it again in the below query($q)
        
    if (empty($errors)) { // If everything's OK.
    
        //  Test for unique email address:
        $q = "SELECT user_id FROM users WHERE email='$e' AND user_id != $id";
        $r = @mysqli_query($dbc, $q);
        if (mysqli_num_rows($r) == 0) { // Not find it, so the email address is unique

            // Make the query to UPDATE the table:
            // PURSUE 2 - add pass=SHA1('$np')
           if (!empty($_POST['pass1'])) {

             $q = "UPDATE users SET first_name='$fn', last_name='$ln', email='$e', pass=SHA1('$np') WHERE user_id=$id LIMIT 1";
           } else { // if no pass1 input, then not update the password in the database
           $q = "UPDATE users SET first_name='$fn', last_name='$ln', email='$e' WHERE user_id=$id LIMIT 1";                                 
           }

                                                                                             
            $r = @mysqli_query ($dbc, $q);
            if (mysqli_affected_rows($dbc == 1) { // If it ran OK.

                // Print a message:
                echo '<p>The user has been edited.</p>';    
                
            } else { // If it did not run OK.
                echo '<p class="error">The user could not be edited due to a system error. We apologize for any inconvenience.</p>'; // Public message.
                echo '<p>' . mysqli_error($dbc) . '<br />Query: ' . $q . '</p>'; // Debugging message.
            }
                
        } else { // Already registered.
            echo '<p class="error">The email address has already been registered.</p>';
        }
        
    } else { // Report the errors.

        echo '<p class="error">The following error(s) occurred:<br />';
        foreach ($errors as $msg) { // Print each error.
            echo " - $msg<br />\n";
        }
        echo '</p><p>Please try again.</p>';
    
    } // End of if (empty($errors)) IF.

} // End of submit conditional.

// Always show the form...

// Retrieve the user's information:
$q = "SELECT first_name, last_name, email FROM users WHERE user_id=$id";        
$r = @mysqli_query ($dbc, $q);

if (mysqli_num_rows($r) == 1) { // Valid user ID, show the form.

      // Get the user's information:
      $row = mysqli_fetch_array ($r, MYSQLI_NUM);

      // PURSUE 3 - form elements’ values come from $_POST, if set, and the database if not
      // Note: if UPDATE check is passed/UPDATE is succeful, then $row[] has the same value as $_POST[]
      $form_fn = isset($_POST['first_name']) ? $_POST['first_name'] : $row[0];
      $form_ln = isset($_POST['last_name']) ? $_POST['last_name'] : $row[1];
      $form_email = isset($_POST['email']) ? $_POST['email'] : $row[2];


      // Create the form:
      // PURSUE 2 - also change a user’s password, adding the new password input and a confirmation
      // PURSUE 3 - substitute original $row[0], $row[1], $row[2] with $form_fn...

      echo '<form action="edit_user.php" method="post">
<p>First Name: <input type="text" name="first_name" size="15" maxlength="15" value="' . $form_fn . '" /></p>
<p>Last Name: <input type="text" name="last_name" size="15" maxlength="30" value="' . $form_ln . '" /></p>
<p>Email Address: <input type="text" name="email" size="20" maxlength="60" value="' . $form_email . '"  /></p>
<p>New Password: <input type="password" name="pass1" size="10" maxlength="20" value="" ></p>
<p>Confirm Password: <input type="password" name="pass2" size="10" maxlength="20" value="" ></p>

<p><input type="submit" name="submit" value="Submit" /></p>
<input type="hidden" name="id" value="' . $id . '" />
</form>';

} else { // Not a valid user ID. If no record was returned from the database, because an invalid user ID was
               // submitted, this message is displayed:
    echo '<p class="error">This page has been accessed in error.</p>';
}

//mysqli_close($dbc);
        
include ('includes/footer.html');
?>

 

 

4. Change the value of the $display variable in view_users.php to alter the pagination.

 

This one is easy, in view_user.php, just modify the constant value:

 

<?php # Script 10.5 - #5
// This script retrieves all the records from the users table.
// This new version allows the results to be sorted in different ways.

$page_title = 'View the Current Users';
include ('includes/header.html');
echo '<h1>Registered Users</h1>';

require ('./mysqli_connect.php');

// Number of records to show per page:
$display = 23;

 

 

 

Link to comment
Share on other sites

Sorry for the delay...busy week...holidays and all...

 

1. Change the delete_user.php and edit_user.php pages so that they both display the user being affected in the browser window’s title bar.

 

Made the change in Header.html:

 

   

   

<?php echo $page_title <span style="color:#ff0000;">. '(' . $_GET['ln'] . ' ' . $_GET['fn'] . ')';</span> ?>

   

 

Then both delete and edit scripts can reflect user's name in browser windows's title bar. One question is for the $_POST case(the form is submitted, and there's no $GET[] value), should we handle it also? If so then I guess I need to write a conditional here in Header.html.

Yes, that's good and right. You can add a conditional to check for $_POST or $_GET.

 

2. Modify edit_user.php so that you can also change a user’s password.

3. If you’re up for a challenge, modify edit_user.php so that the form elements’ values come from $_POST, if set, and the database if not.

 

<?php # Script 10.3 - edit_user.php - PURSUE

// This page is for editing a user record.

// This page is accessed through view_users.php.

 

$page_title = 'Edit a User';

include ('includes/header.html');

echo '

Edit a User

';

 

// Check for a valid user ID, through GET or POST:

if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_users.php

    $id = $_GET['id'];

} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.

    $id = $_POST['id'];

} else { // No valid ID, kill the script.

    echo '

This page has been accessed in error.

';

    include ('includes/footer.html');

    exit();

}

 

require ('./mysqli_connect.php');

 

// Check if the form has been submitted:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

 

    $errors = array();

    

    // Check for a first name:

    if (empty($_POST['first_name'])) {

        $errors[] = 'You forgot to enter your first name.';

    } else {

        $fn = mysqli_real_escape_string($dbc, trim($_POST['first_name']));

    }

    

    // Check for a last name:

    if (empty($_POST['last_name'])) {

        $errors[] = 'You forgot to enter your last name.';

    } else {

        $ln = mysqli_real_escape_string($dbc, trim($_POST['last_name']));

    }

 

    // Check for an email address:

    if (empty($_POST['email'])) {

        $errors[] = 'You forgot to enter your email address.';

    } else {

        $e = mysqli_real_escape_string($dbc, trim($_POST['email']));

    }

    

    // PURSUE 2 - Check for a NEW password(updated) and match against the confirmed password:

        //If these values are submitted, update the password in the database as well. If these inputs are left blank, do not update the password in the database.(do not put an error message in $errors[] & use the original $q)

    if (!empty($_POST['pass1'])) {

        if ($_POST['pass1'] != $_POST['pass2']) {

            $errors[] = 'Your new password did not match the confirmed password.';

        } else {

            $np = mysqli_real_escape_string($dbc, trim($_POST['pass1']));

        }

    } // if pass1 is empty, then do nothing here, delete the original else statement. But nend to add judge it again in the below query($q)

        

    if (empty($errors)) { // If everything's OK.

    

        //  Test for unique email address:

        $q = "SELECT user_id FROM users WHERE email='$e' AND user_id != $id";

        $r = @mysqli_query($dbc, $q);

        if (mysqli_num_rows($r) == 0) { // Not find it, so the email address is unique

 

            // Make the query to UPDATE the table:

            // PURSUE 2 - add pass=SHA1('$np')

           if (!empty($_POST['pass1'])) {

             $q = "UPDATE users SET first_name='$fn', last_name='$ln', email='$e', pass=SHA1('$np') WHERE user_id=$id LIMIT 1";

           } else { // if no pass1 input, then not update the password in the database

           $q = "UPDATE users SET first_name='$fn', last_name='$ln', email='$e' WHERE user_id=$id LIMIT 1";                                 

           }

                                                                                             

            $r = @mysqli_query ($dbc, $q);

            if (mysqli_affected_rows($dbc == 1) { // If it ran OK.

 

                // Print a message:

                echo '

The user has been edited.

';    

                

            } else { // If it did not run OK.

                echo '

The user could not be edited due to a system error. We apologize for any inconvenience.

'; // Public message.

                echo '

' . mysqli_error($dbc) . '

Query: ' . $q . '

'; // Debugging message.

            }

                

        } else { // Already registered.

            echo '

The email address has already been registered.

';

        }

        

    } else { // Report the errors.

 

        echo '

The following error(s) occurred:

';

        foreach ($errors as $msg) { // Print each error.

            echo " - $msg

\n";

        }

        echo '

Please try again.

';

    

    } // End of if (empty($errors)) IF.

 

} // End of submit conditional.

 

// Always show the form...

 

// Retrieve the user's information:

$q = "SELECT first_name, last_name, email FROM users WHERE user_id=$id";        

$r = @mysqli_query ($dbc, $q);

 

if (mysqli_num_rows($r) == 1) { // Valid user ID, show the form.

 

      // Get the user's information:

      $row = mysqli_fetch_array ($r, MYSQLI_NUM);

 

      // PURSUE 3 - form elements’ values come from $_POST, if set, and the database if not

      // Note: if UPDATE check is passed/UPDATE is succeful, then $row[] has the same value as $_POST[]

      $form_fn = isset($_POST['first_name']) ? $_POST['first_name'] : $row[0];

      $form_ln = isset($_POST['last_name']) ? $_POST['last_name'] : $row[1];

      $form_email = isset($_POST['email']) ? $_POST['email'] : $row[2];

 

      // Create the form:

      // PURSUE 2 - also change a user’s password, adding the new password input and a confirmation

      // PURSUE 3 - substitute original $row[0], $row[1], $row[2] with $form_fn...

      echo '

First Name: $form_fn . '" />

Last Name: $form_ln . '" />

Email Address: $form_email . '"  />

New Password:

Confirm Password:

';

 

} else { // Not a valid user ID. If no record was returned from the database, because an invalid user ID was

               // submitted, this message is displayed:

    echo '

This page has been accessed in error.

';

}

 

//mysqli_close($dbc);

        

include ('includes/footer.html');

?>

Looks really good! 

 

4. Change the value of the $display variable in view_users.php to alter the pagination.

 

This one is easy, in view_user.php, just modify the constant value:

 

<?php # Script 10.5 - #5

// This script retrieves all the records from the users table.

// This new version allows the results to be sorted in different ways.

 

$page_title = 'View the Current Users';

include ('includes/header.html');

echo '

Registered Users

';

 

require ('./mysqli_connect.php');

 

// Number of records to show per page:

$display = 23;

Yep. Nicely done and thanks for sharing!

Link to comment
Share on other sites

 Share

×
×
  • Create New...