Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

This chapter is from the book


The registration form needs to present fields for everything being stored in the database. Plus, it’s common to have users confirm their password, just to make sure they know what it is (since password inputs don’t display the entered text, it’s easy to unknowingly make a mistake). The same PHP script will display the form and handle its results. Therefore, if the registration form is incomplete, it can be shown again, with the existing values in place, along with detailed error messages (Figure 4.3).

The registration script I came up with, which you can download from, is about 160 lines total, including comments. Rather than walk you through the entire script in one long series of steps, let’s look at this script as its three distinct parts.

Creating the Basic Shell

Every PHP page in the site—every script that a user will access directly and that won’t be included by other PHP scripts—has the same basic structure. First, it includes the configuration file; then the MySQL connection script; and then the HTML header (likely setting the page title beforehand). Next comes the page-specific content, and finally, the footer is included. Here, then, is what you can start with for register.php:

$page_title = 'Register';

<p>Access to the site's content is available to registered users at a cost of $10.00 (US) per year. Use the form below to begin the registration process. <strong>Note: All fields are required.</strong> After completing this form, you'll be presented with the opportunity to securely pay for your yearly subscription via <a href="">PayPal</a>.</p>

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

For the registration page, it’s important that you give the customer a sense of the process. You may want to graphically indicate the steps involved using a progress bar (or progress meter), although the process of registering for this site has only two steps. Also indicate how all the data will be used (for example, explain that the user won’t be spammed), and maybe refer the user to whatever site policies exist (I’ve created a link to a policy file in the footer). Just do everything you can to reassure the user that it’s safe to proceed.

Creating the Form

The registration form contains six inputs: four text and two password (plus the submit button). I’ve already defined a function for creating these inputs, so the first thing the registration form needs to do is include the file. Do this just before the page-specific content:


As a complication, the script may already have been included by the header file (to make the login form). To ensure that is also available here, without seeing an error for possibly including it a second time, the require_once() function is the appropriate way to include that file before the registration form.

The form itself looks like this:

<form action="register.php" method="post" accept-charset="utf-8">
create_form_input('first_name', 'text', 'First Name', $reg_errors);
create_form_input('last_name', 'text', 'Last Name', $reg_errors);
create_form_input('username', 'text', 'Desired Username', $reg_errors);
echo '<span class="help-block">Only letters and numbers are allowed.</span>';
create_form_input('email', 'email', 'Email Address', $reg_errors);
create_form_input('pass1', 'password', 'Password', $reg_errors);
echo '<span class="help-block">Must be at least 6 characters long, with at least one lowercase letter, one uppercase letter, and one number.</span>';
create_form_input('pass2', 'password', 'Confirm Password', $reg_errors);
<input type="submit" name="submit_button" value="Next &rarr;" id="submit_button" class="btn btn-default" />

You’ll see that with the aid of the create_form_input() function, all the code for creating each input and handling all the errors is extremely simple. As an example, for the first name input, the function is called indicating that the input should have name and id values of first_name, should be of text type, and should use First Name as the label. The fourth argument to the function is an array of errors named $reg_errors. In a few pages, this array will be added to the registration script so that it’s already defined prior to this point. The same function is called for all six inputs, changing the arguments accordingly.

For the username and passwords, the user is being presented with a clear indication of what’s expected of them. It drives me crazy when sites complain that I didn’t complete a form properly (such as by not using at least one number or capital letter in a password) when no such instructions were included.

Processing the Form

The bulk of the register.php script is the validation of the form and the insertion of the new record into the database. That part of the script is over one hundred lines of code, so I’ll walk through it more deliberately. Figure 4.4 shows a flowchart of how this entire page will be used and may help you understand what’s going on with the code. Note that all the code in the steps that follow gets placed after the MySQL connection script is included—because you’ll need access to the database—but before the include and the page-specific content. Again, see the downloadable scripts if you’re confused about the order of things.

  1. Create an empty array for storing errors:

    $reg_errors = array();

    This array will be used to store any errors that occur during the validation process. Normally, I might include this line within the section that begins the validation process (see Step 2), but because the create_form_input() function calls are going to use $reg_errors the very first time the page is loaded, you need to create this empty array at this point.

  2. Check for a form submission:

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

    The first time the user goes to register.php (that is, when the user loads the form), it will be a GET request. In that case, this conditional, and all the code to follow, won’t apply. When the user clicks submit, a POST request will be made of register.php, and this code will be executed.

  3. Check for a first name:

    if (preg_match ('/^[A-Z \'.-]{2,45}$/i', $_POST['first_name'])) {
       $fn = escape_data($_POST['first_name'], $dbc);
    } else {
       $reg_errors['first_name'] = 'Please enter your first name!';

    Names are difficult to validate, so I’m using a regular expression that’s neither too strict nor too lenient. The pattern insists that the submitted value be between 2 and 45 characters long and only contain a combination of letters (case-insensitive), the space, a period, an apostrophe, and a hyphen. If the value passes this test, the escaped version of that value is assigned to the $fn variable. If the value doesn’t pass this test, a new element is added to the $reg_errors array. The element uses the same key as the form input so that the create_form_input() function can properly display the error.

    Alternatively, you could just check that this value isn’t empty, and then run it through strip_tags() to make sure it doesn’t contain anything it shouldn’t.

  4. Check for a last name:

    if (preg_match ('/^[A-Z \'.-]{2,45}$/i', $_POST['last_name'])) {
       $ln = escape_data($_POST['last_name'], $dbc);
    } else {
       $reg_errors['last_name'] = 'Please enter your last name!';

    This is the same code as for the first name, but with a longer maximum length.

  5. Check for a username:

    if (preg_match ('/^[A-Z0-9]{2,45}$/i', $_POST['username'])) {
       $u = escape_data($_POST['username'], $dbc);
    } else {
       $reg_errors['username'] = 'Please enter a desired name using only letters and numbers!';

    The username, per the instructions indicated in the form, is restricted to just letters and numbers. The username has to be between 2 and 45 characters long.

  6. Check for an email address:

    if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
       $e = escape_data($_POST['email'], $dbc);
    } else {
       $reg_errors['email'] = 'Please enter a valid email address!';

    Unlike names, email addresses have to adhere to a fairly strict syntax. The simplest and most fail-safe way to validate an email address is to use PHP’s filter_var() function, part of the Filter extension added in PHP 5.2. Its first argument is the variable to be tested, and its second is a constant representing a validation model.

    If you’re not using a version of PHP that supports the Filter extension, you’ll need to use a regular expression instead (you can find good patterns online and in my books).

  7. Check for a password and match against the confirmed password:

    if (preg_match('/^(\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*){6,}$/', $_POST['pass1']) ) {
       if ($_POST['pass1'] === $_POST['pass2']) {
          $p = $_POST['pass1'];
       } else {
          $reg_errors['pass2'] = 'Your password did not match the confirmed password!';
    } else {
       $reg_errors['pass1'] = 'Please enter a valid password!';

    OK, so, um, here’s a little magic for you. Good validation normally uses regular expressions, with which not everyone is entirely comfortable. And, admittedly, I often have to look up the proper syntax for patterns, but this one requires a high level of regular expression expertise. For the password to be relatively secure, it needs to contain at least one uppercase letter, one lowercase letter, and one number. In other words, it can’t just be a word out of the dictionary, all in one case. Creating a regular expression that confirms that these characters exist in the password, but in any position in the string, requires what’s called a zero-width positive lookahead assertion, represented by the ?=. The positive lookahead makes matches based on what follows a character. Rather than reading a page of explanation as to how this pattern works beyond that simple definition, you can test it for yourself to confirm that it does and research zero-width positive lookahead assertions online if you’re curious.

    Note that the password doesn’t need to be run through the escape_data() function. The password itself won’t be used in a query, but rather the hash of the password will be.

  8. If there are no errors, check the availability of the email address and username:

    if (empty($reg_errors)) {
       $q = "SELECT email, username FROM users WHERE email='$e' OR username='$u'";
       $r = mysqli_query($dbc, $q);
       $rows = mysqli_num_rows($r);
       if ($rows === 0) {

    If the $reg_errors array is still empty, no errors occurred (because even one error would add an element to this array, making it no longer empty). Next, a query looks for any existing record that has the submitted email address or username. In theory, this query could return up to two records (one for the email address and one for the username); if it returns no records, it’s safe to proceed.

  9. Add the user to the database:

    $q = "INSERT INTO users (username, email, pass, first_name, last_name, date_expires) VALUES ('$u', '$e', '"  .  password_hash($p, PASSWORD_BCRYPT) .  "', '$fn', '$ln', ADDDATE(NOW(), INTERVAL 1 MONTH) )";
    $r = mysqli_query($dbc, $q);

    The query uses the submitted values to create a new record in the database. Note that for the password value, the password_hash() function is called. If you’re not using PHP 5.5 or later, you’ll need to install and include the password_compat library prior to this first line.

    The user’s type doesn’t need to be set because if no value is provided for an ENUM column, the first enumerated value—here, member—will be used.

    Until PayPal is integrated (see Chapter 6, “Using PayPal”), I’m setting the account expiration date to a month from now. Once PayPal has been integrated, the expiration will be set to yesterday. In that case, when PayPal returns an indication of successful payment, the user’s account will subsequently be set to expire in a year.

  10. If the query created one row, thank the new customer and send out an email:

    if (mysqli_affected_rows($dbc) === 1) {
       echo '<div class="alert alert-success"><h3>Thanks!</h3><p>Thank you for registering! You may now log in and access the site\'s content.</p></div>';
       $body = "Thank you for registering at <whatever site>. Blah. Blah. Blah.\n\n";
       mail($_POST['email'], 'Registration Confirmation', $body, 'From:');

    First, a Thanks! page is displayed (Figure 4.5). The next step would be to send the user off to PayPal, which will be added in Chapter 6. Also, an email can be sent to the user saying whatever you want, although you shouldn’t include the user’s password in that email. Finally, the footer is included and a call to exit() stops the page. This is necessary so that the registration form isn’t shown again, thereby confusing the user.

  11. If the query didn’t work, create an error:

    } else {
       trigger_error('You could not be registered due to a system error. We apologize for any inconvenience. We will correct the error ASAP.');

    At this point, if the query didn’t create a new row, there was a database or query error. In that case, the trigger_error() function is used to generate an error that will be managed by the error handler in the config file. On a live, already tested site, this would likely occur only if the database server is down or overloaded.

  12. If the email address or username is unavailable, create errors:

    if ($rows === 2) {
       $reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link at left to have your password sent to you.';
       $reg_errors['username'] = 'This username has already been registered. Please try another.';

    The else clause applies if the SELECT query returns any records. This means that the email address and/or the username have already been registered. If so, the next step is to determine which of the two values is the culprit.

    If two rows were returned, both have already been registered. The assumption would be that the same customer already registered (because her email address is in the system) and another customer already has that username (because it’s associated with a different email address). The error messages are added to the $reg_errors array, indexed at email and username, so that the errors can appear beside the appropriate form input when the form is redisplayed.

  13. Confirm which item has been registered:

    } else {
       $row = mysqli_fetch_array($r, MYSQLI_NUM);
       if( ($row[0] === $_POST['email']) && ($row[1] === $_POST['username'])) {
          $reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link at left to have your password sent to you.';
          $reg_errors['username'] = 'This username has already been registered with this email address. If you have forgotten your password, use the link at left to have your password sent to you.';
       } elseif ($row[0] === $_POST['email']) {
          $reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link at left to have your password sent to you.';
       } elseif ($row[1] === $_POST['username']) {
          $reg_errors['username'] = 'This username has already been registered. Please try another.';
    } // End of $rows === 2 ELSE.

    If only one row was returned, the code needs to figure out if the username matched, the email address matched, or both matched in the same record. Three conditionals test for each possibility, with appropriate error messages assigned (Figures 4.6 and 4.7).

  14. Complete the conditionals:

          } // End of $rows === 0 IF.
       } // End of empty($reg_errors) IF.
    } // End of the main form submission conditional.
  15. Save and test the registration script.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive:

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020