Jump to content
Larry Ullman's Book Forums

Ch9, My Solution To Pursue Exercises


Recommended Posts

Hi all,

 

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

 

1. Change the use of mysqli_num_rows( ) in view_users.php so that it’s only called if the query had a TRUE result.

 

<?php # Script 9.6 - view_users.php #2 - PURSUE
#Change the use of mysqli_num_rows( )in view_users.php so that it’s only called #if the query had a TRUE result.

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

$page_title = 'View the Current Users';
include ('includes/header.html');

// Page header:
echo '<h1>Registered Users</h1>';

require ('./mysqli_connect.php'); // Connect to the db.
        
// Make the query:
$q = "SELECT CONCAT(last_name, ', ', first_name) AS name, DATE_FORMAT(registration_date, '%M %d, %Y') AS dr FROM users ORDER BY registration_date ASC";        
$r = @mysqli_query ($dbc, $q); // Run the query.

if($r) { // PURSUE - mysqli_num_rows( ) is only called when the query has a TRUE result
      // Count the number of returned rows:
      $num = mysqli_num_rows($r);

      if ($num > 0) { // If it ran OK, display the records.

              // Print how many users there are:
              echo "<p>There are currently $num registered users.</p>\n";

              // Table header.
              echo '<table align="center" cellspacing="3" cellpadding="3" width="75%">
              <tr><td align="left"><b>Name</b></td><td align="left"><b>Date Registered</b></td></tr>
      ';

              // Fetch and print all the records:
              while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
                      echo '<tr><td align="left">' . $row['name'] . '</td><td align="left">' . $row['dr'] . '</td></tr>
                      ';
              }

              echo '</table>'; // Close the table.

              mysqli_free_result ($r); // Free up the resources.    

      } else { // If no records were returned.

              echo '<p class="error">There are currently no registered users.</p>';

      }
} else { // Handle the situation that the query has no correct result
      // Public message:
      echo '<p class="error">The query was incorrect. We apologize for any inconvenience.</p>';

      // Debugging message:
      echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
}


mysqli_close($dbc); // Close the database connection.

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

 

 

 

----------

1. Apply the mysqli_num_rows( ) function to register.php, as suggested in an earlier sidebar.
2. Apply the mysqli_affected_rows( ) function to register.php to confirm that the INSERT worked.

 

<?php # Script 9.5 - register.php #2 - PURSUE
#1. Apply the mysqli_num_rows( ) function to register.php to prevent someone from registering with
#   the same email address multiple times
#2. Apply the mysqli_affected_rows( )function to register.php to confirm that the INSERT worked.

// This script performs an INSERT query to add a record to the users table.

$page_title = 'Register';
include ('includes/header.html');

// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    require ('./mysqli_connect.php'); // Connect to the db.  
        
    $errors = array(); // Initialize an error 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 { // User entered email address
           $e = mysqli_real_escape_string($dbc, trim($_POST['email']));
           $q = "SELECT user_id FROM users WHERE email = '$e'";
// PURSUE 1 - confirm the email address isn’t currently registered.
           $r = @mysqli_query($dbc, $q);
           $num = mysqli_num_rows($r);  
           if ($num != 0) { // Result table is NOT empty, meaning the email address already existed
          $errors[] = 'This email address has already been registered.'; // Add error message to $errors so INSERT won't happen later     

           }                                                     
    }

                
    // Check for a password and match against the confirmed password:
    if (!empty($_POST['pass1'])) {
        if ($_POST['pass1'] != $_POST['pass2']) {
            $errors[] = 'Your password did not match the confirmed password.';
        } else {
            $p = mysqli_real_escape_string($dbc, trim($_POST['pass1']));
        }
    } else {
        $errors[] = 'You forgot to enter your password.';
    }
    
    if (empty($errors)) { // If everything's OK.
    
        // Register the user in the database...
        
        // Make the query:
        $q = "INSERT INTO users (first_name, last_name, email, pass, registration_date) VALUES ('$fn', '$ln', '$e', SHA1('$p'), NOW() )";        
        $r = @mysqli_query ($dbc, $q); // Run the query.
        //if ($r) { // If it ran OK.
        if (mysqli_affected_rows($dbc) == 1) { // PURSUE 2 - If the INSERT worked

                        
            // Print a message:
            echo '<h1>Thank you!</h1>
        <p>You are now registered. In Chapter 12 you will actually be able to log in!</p><p><br /></p>';    
        
        } else { // If INSERT did not run OK.
            
            // Public message:
            echo '<h1>System Error</h1>
            <p class="error">You could not be registered due to a system error. We apologize for any inconvenience.</p>';
            
            // Debugging message:
            echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
                        
        } // End of if ($r) IF.
        
        mysqli_close($dbc); // Close the database connection.

        // Include the footer and quit the script:
        include ('includes/footer.html');
        exit();
        
    } else { // Report the errors.
    
        echo '<h1>Error!</h1>
        <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><p><br /></p>';
        
    } // End of if (empty($errors)) IF.
    
    mysqli_close($dbc); // Close the database connection. NEW, to match the open in the begining of the conditional

} // End of the main Submit conditional.
?>
<h1>Register</h1>
<form action="" method="post">
    <p>First Name: <input type="text" name="first_name" size="15" maxlength="20" value="<?php if (isset($_POST['first_name'])) echo $_POST['first_name']; ?>" /></p>
    <p>Last Name: <input type="text" name="last_name" size="15" maxlength="40" value="<?php if (isset($_POST['last_name'])) echo $_POST['last_name']; ?>" /></p>
    <p>Email Address: <input type="text" name="email" size="20" maxlength="60" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>"  /> </p>
    <p>Password: <input type="password" name="pass1" size="10" maxlength="20" value="<?php if (isset($_POST['pass1'])) echo $_POST['pass1']; ?>"  /></p>
    <p>Confirm Password: <input type="password" name="pass2" size="10" maxlength="20" value="<?php if (isset($_POST['pass2'])) echo $_POST['pass2']; ?>"  /></p>
    <p><input type="submit" name="submit" value="Register" /></p>
</form>
<?php include ('includes/footer.html'); ?>

 

 

 

Link to comment
Share on other sites

 Share

×
×
  • Create New...