Tuesday, May 15, 2012

Adding New Users

This post will detail how I added the functionality to add new users for Coursework 2.

A simple form was written using HTML and CSS. All that is needed from the user is a username and a password.

About the Form Layout

I opted for a less traditional vertical layout for the sign-up form. Studies have shown that this (instead a standard 2 column left-right form) increases user engagement.

The form passes the account details to a PHP script called "insertAccount.php".

Cleaning the Input

I opted to remove all spaces from the username $u, and it is then escaped. The password $p is simply stored as-is for now.

$u = str_replace(" ", "", $_POST['username']);
$u = mysql_real_escape_string($u);

$p = $_POST['password'];

Checking for Errors

A chain of if-else statements is used to confirm that the data the user entered is valid. If something isn't entered correctly, the page will redirect back with the error. A list of the 3 conditions is below:

  • The password must be at least 6 characters long.
  • The 2 passwords entered must match.
  • The username field must not be empty.

Once all the checks are performed, the password is hashed, and the SQL is executed.

if (strlen($p) < 6) {
} else if ($_POST['password'] != $_POST['password2']) {
} else if (empty($u)) {
} else {
 $p = hashPassword($_POST['password']);
 $result = executeQuery("insert into user (username, password) values ('" . $u . "', '" . $p . "')");

The only way for the SQL executed to fail is if the user already exists. This is communicated to the user.

Below is the error message for the password field.

Successful Sign-Up

If all goes well, the user is registered, and a welcome message is issued.

They are then offered to go to the log in page.


This post detailed how to clean user input, check for errors, and insert a user account into the MySQL database.

Download Source Code

You can download the source code below.

No comments:

Post a Comment