PHP User Registration Form (Sign up) with MySQL Database

Last modified on July 23rd, 2019 by Vincy.

User registration or sign up is an integral part of many web applications and it is critical to get it right for the success of the application. It is the starting point of user engagement with your application.

It should be as simple as possible with best UI / UX. Implementing user registration functionality using PHP is a simple task and I will walk you through the steps with example in this article.

View Demo

PHP User Registration Form Screenshot

What is inside?

  1. How this PHP user registration example works?
  2. File structure
  3. HTML form to allow user to register
  4. How to validate user information on form submit
  5. PHP MySQL code to access database to save registered user
  6. Database script

How this PHP user registration example works?

This example code can be separated into 3 parts.

  1. Getting user information via a HTML form.
  2. Validating user submitted information on form submit.
  3. Database handling to save registered user to the database after validation.

The third step will be executed after ensuring that the user is not added already. This data uniqueness validation will be performed based on their email and username entered by them.

During registration we generally collect user information, who are ready to register with our application. Some of them will be mandatory and some of them will be optional.

So, this functionality may also include validation part to ensure about the non-emptiness and the format of the user data.  The validation could be done either in client-side or server side.

Having validation at server-side is always better. You can choose to have it in client-side also for the ease of  use of the users. But having at the server-side is not optional and a minimum requirement.

File structure

PHP User Registration File Structure

HTML form to allow user to register

In this example, the registration form contains the fields Username, Name(Display Name), Password and Email. It also has the Confirm Password field to let the user to reenter his password for the confirmation. These two passwords will be compared later at the time of a server-side validation.

By submitting this form, the user is expected to agree the terms and conditions. So a checkbox field is added before the Register button for ensuring it.

<html>
<head>
<title>PHP User Registration Form</title>
<link href="./css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form name="frmRegistration" method="post" action="">
        <div class="demo-table">
        <div class="form-head">Sign Up</div>
            
<?php
if (! empty($errorMessage) && is_array($errorMessage)) {
    ?>	
            <div class="error-message">
            <?php 
            foreach($errorMessage as $message) {
                echo $message . "<br/>";
            }
            ?>
            </div>
<?php
}
?>
            <div class="field-column">
                <label>Username</label>
                <div>
                    <input type="text" class="demo-input-box"
                        name="userName"
                        value="<?php if(isset($_POST['userName'])) echo $_POST['userName']; ?>">
                </div>
            </div>
            
            <div class="field-column">
                <label>Password</label>
                <div><input type="password" class="demo-input-box"
                    name="password" value=""></div>
            </div>
            <div class="field-column">
                <label>Confirm Password</label>
                <div>
                    <input type="password" class="demo-input-box"
                        name="confirm_password" value="">
                </div>
            </div>
            <div class="field-column">
                <label>Display Name</label>
                <div>
                    <input type="text" class="demo-input-box"
                        name="firstName"
                        value="<?php if(isset($_POST['firstName'])) echo $_POST['firstName']; ?>">
                </div>

            </div>
            <div class="field-column">
                <label>Email</label>
                <div>
                    <input type="text" class="demo-input-box"
                        name="userEmail"
                        value="<?php if(isset($_POST['userEmail'])) echo $_POST['userEmail']; ?>">
                </div>
            </div>
            <div class="field-column">
                <div class="terms">
                    <input type="checkbox" name="terms"> I accept terms
                    and conditions
                </div>
                <div>
                    <input type="submit"
                        name="register-user" value="Register"
                        class="btnRegister">
                </div>
            </div>
        </div>
    </form>
</body>
</html>

And the styles are,

body {
    font-family: Arial;
    color: #333;
    font-size: 0.95em;
}

.form-head {
    color: #191919;
    font-weight: normal;
    font-weight: 400;
    margin: 0;
    text-align: center;    
    font-size: 1.8em;
}

.error-message {
    padding: 7px 10px;
    background: #fff1f2;
    border: #ffd5da 1px solid;
    color: #d6001c;
    border-radius: 4px;
    margin: 30px 0px 10px 0px;
}

.success-message {
    padding: 7px 10px;
    background: #cae0c4;
    border: #c3d0b5 1px solid;
    color: #027506;
    border-radius: 4px;
    margin: 30px 0px 10px 0px;
}

.demo-table {
    background: #ffffff;
    border-spacing: initial;
    margin: 15px auto;
    word-break: break-word;
    table-layout: auto;
    line-height: 1.8em;
    color: #333;
    border-radius: 4px;
    padding: 20px 40px;
    width: 380px;
    border: 1px solid;
    border-color: #e5e6e9 #dfe0e4 #d0d1d5;
}

.demo-table .label {
    color: #888888;
}

.demo-table .field-column {
    padding: 15px 0px;
}

.demo-input-box {
    padding: 13px;
    border: #CCC 1px solid;
    border-radius: 4px;
    width: 100%;
}

.btnRegister {
    padding: 13px;
    background-color: #5d9cec;
    color: #f5f7fa;
    cursor: pointer;
    border-radius: 4px;
    width: 100%;
    border: #5791da 1px solid;
    font-size: 1.1em;
}

.response-text {
    max-width: 380px;
    font-size: 1.5em;
    text-align: center;
    background: #fff3de;
    padding: 42px;
    border-radius: 3px;
    border: #f5e9d4 1px solid;
    font-family: arial;
    line-height: 34px;
    margin: 15px auto;
}

.terms {
    margin-bottom: 5px;
}

How to validate user information on form submit

A server-side form validation script is added in this example for validating the user registration data. This PHP validation script will be called on submitting the registration form.

This script validates all form fields to check the non-emptiness for each field. Then it validates the user email format using PHP filter_var() function.

As the registration includes password confirmation feature, the password comparison will take place at this part of this example.

Finally, the validation script will check if the user accepts term and condition by checking the appropriate box on the form.

Once all the validation completed by returning boolean true, then the actual registration process will take place.

function validateMember()
{
    $valid = true;
    $errorMessage = array();
    foreach ($_POST as $key => $value) {
        if (empty($_POST[$key])) {
            $valid = false;
        }
    }
    
    if($valid == true) {
        if ($_POST['password'] != $_POST['confirm_password']) {
            $errorMessage[] = 'Passwords should be same.';
            $valid = false;
        }
        
        if (! isset($error_message)) {
            if (! filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) {
                $errorMessage[] = "Invalid email address.";
                $valid = false;
            }
        }
        
        if (! isset($error_message)) {
            if (! isset($_POST["terms"])) {
                $errorMessage[] = "Accept terms and conditions.";
                $valid = false;
            }
        }
    }
    else {
        $errorMessage[] = "All fields are required.";
    }
    
    if ($valid == false) {
        return $errorMessage;
    }
    return;
}

PHP MySQL code to access database to save registered user

Server-side user form validation

This is the PHP entry point to handle all the server-side script to validate form and to handle database operations based on the validation result.

<?php
namespace Phppot;

use \Phppot\Member;
if (! empty($_POST["register-user"])) {
    
    $username = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
    $displayName = filter_var($_POST["firstName"], FILTER_SANITIZE_STRING);
    $password = filter_var($_POST["password"], FILTER_SANITIZE_STRING);
    $email = filter_var($_POST["userEmail"], FILTER_SANITIZE_STRING);
    require_once ("Member.php");
    /* Form Required Field Validation */
    $member = new Member();
    $errorMessage = $member->validateMember($username, $displayName, $password, $email);
    
    if (empty($errorMessage)) {
        $memberCount = $member->isMemberExists($username, $email);
        
        if ($memberCount == 0) {
            $insertId = $member->insertMemberRecord($username, $displayName, $password, $email);
            if (! empty($insertId)) {
                header("Location: thankyou.php");
            }
        } else {
            $errorMessage[] = "User already exists.";
        }
    }
}
?>

Check if user already exists

The isMemberExists() function is used to check the user data uniqueness based on their email and the username. If the entered username or email there exists in the user database, then the registration process will be stopped by returning and acknowledgement.

This acknowledgement will notify that the “user already exists”. The code is,

function isMemberExists($username, $email)
{
    $query = "select * FROM registered_users WHERE user_name = ? OR email = ?";
    $paramType = "ss";
    $paramArray = array($username, $email);
    $memberCount = $this->ds->numRows($query, $paramType, $paramArray);
    
    return $memberCount;
}

Insert member data to the database

If it returns 0 then it means that there is no such users exist with the email or the username entered. And so, the registration data will be inserted to the database. The following code shows the member insert method.

function insertMemberRecord($username, $displayName, $password, $email)
{
    $passwordHash = md5($password);
    $query = "INSERT INTO registered_users (user_name, display_name, password, email) VALUES (?, ?, ?, ?)";
    $paramType = "ssss";
    $paramArray = array(
        $username,
        $displayName,
        $passwordHash,
        $email
    );
    $insertId = $this->ds->insert($query, $paramType, $paramArray);
    return $insertId;
}

DataSource.php

This is the generic data source class in PHP to perform database operations. It includes functions to connect database and execute various queries to get database result, row count, execute insert and more.

This datasource class is generic and kept as simple as possible. It is efficient and I use it in my most of the micro projects and tutorials. You are free to download and use it.

Important thing is never forget to use the Prepared Statements. It helps you to safeguard from SQL injection attacks and it is the first step in terms of implementing security in a web application.

<?php
namespace Phppot;

/**
 * Generic datasource class for handling DB operations.
 * Uses MySqli and PreparedStatements.
 *
 * @version 2.3
 */
class DataSource
{

    // PHP 7.1.0 visibility modifiers are allowed for class constants.
    // when using above 7.1.0, declare the below constants as private
    const HOST = 'localhost';

    const USERNAME = 'root';

    const PASSWORD = '';

    const DATABASENAME = 'phpsamples';

    private $conn;

    /**
     * PHP implicitly takes care of cleanup for default connection types.
     * So no need to worry about closing the connection.
     *
     * Singletons not required in PHP as there is no
     * concept of shared memory.
     * Every object lives only for a request.
     *
     * Keeping things simple and that works!
     */
    function __construct()
    {
        $this->conn = $this->getConnection();
    }

    /**
     * If connection object is needed use this method and get access to it.
     * Otherwise, use the below methods for insert / update / etc.
     *
     * @return \mysqli
     */
    public function getConnection()
    {
        $conn = new \mysqli(self::HOST, self::USERNAME, self::PASSWORD, self::DATABASENAME);
        
        if (mysqli_connect_errno()) {
            trigger_error("Problem with connecting to database.");
        }
        
        $conn->set_charset("utf8");
        return $conn;
    }

    /**
     * To get database results
     * @param string $query
     * @param string $paramType
     * @param array $paramArray
     * @return array
     */
    public function select($query, $paramType="", $paramArray=array())
    {
        $stmt = $this->conn->prepare($query);
        
        if(!empty($paramType) && !empty($paramArray)) {
            $this->bindQueryParams($sql, $paramType, $paramArray);
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $resultset[] = $row;
            }
        }
        
        if (! empty($resultset)) {
            return $resultset;
        }
    }
    
    /**
     * To insert
     * @param string $query
     * @param string $paramType
     * @param array $paramArray
     * @return int
     */
    public function insert($query, $paramType, $paramArray)
    {
        print $query;
        $stmt = $this->conn->prepare($query);
        $this->bindQueryParams($stmt, $paramType, $paramArray);
        $stmt->execute();
        $insertId = $stmt->insert_id;
        return $insertId;
    }
    
    /**
     * To execute query
     * @param string $query
     * @param string $paramType
     * @param array $paramArray
     */
    public function execute($query, $paramType="", $paramArray=array())
    {
        $stmt = $this->conn->prepare($query);
        
        if(!empty($paramType) && !empty($paramArray)) {
            $this->bindQueryParams($stmt, $paramType="", $paramArray=array());
        }
        $stmt->execute();
    }
    
    /**
     * 1. Prepares parameter binding
     * 2. Bind prameters to the sql statement
     * @param string $stmt
     * @param string $paramType
     * @param array $paramArray
     */
    public function bindQueryParams($stmt, $paramType, $paramArray=array())
    {
        $paramValueReference[] = & $paramType;
        for ($i = 0; $i < count($paramArray); $i ++) {
            $paramValueReference[] = & $paramArray[$i];
        }
        call_user_func_array(array(
            $stmt,
            'bind_param'
        ), $paramValueReference);
    }
    
    /**
     * To get database results
     * @param string $query
     * @param string $paramType
     * @param array $paramArray
     * @return array
     */
    public function numRows($query, $paramType="", $paramArray=array())
    {
        $stmt = $this->conn->prepare($query);
        
        if(!empty($paramType) && !empty($paramArray)) {
            $this->bindQueryParams($stmt, $paramType, $paramArray);
        }
        
        $stmt->execute();
        $stmt->store_result();
        $recordCount = $stmt->num_rows;
        return $recordCount;
    }
}

Database script

This database script has the create statement for the registered_users table. Import this script in your development environment to run this code.

--
-- Table structure for table `registered_users`
--

CREATE TABLE IF NOT EXISTS `registered_users` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) NOT NULL,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `password` varchar(25) NOT NULL,
  `email` varchar(55) NOT NULL,
  `gender` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
);

If the registration form validation fails, then the error message will be shown to the user as like as below.

Registration Form Validation Message

View DemoDownload

Comments to “PHP User Registration Form (Sign up) with MySQL Database”

  • Ray says:

    Hi Vincy, I get the following errors when running the register code, please help.

    INSERT INTO registered_users (user_name, display_name, password, email) VALUES (?, ?, ?, ?)
    Warning: call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object in C:\xampp\htdocs\PHP\JAMII-CASH\DataSource.php on line 136

    Fatal error: Uncaught Error: Call to a member function execute() on boolean in C:\xampp\htdocs\PHP\JAMII-CASH\DataSource.php:99 Stack trace: #0 C:\xampp\htdocs\PHP\JAMII-CASH\Member.php(83): Phppot\DataSource->insert(‘INSERT INTO reg…’, ‘ssss’, Array) #1 C:\xampp\htdocs\PHP\JAMII-CASH\index.php(20): Phppot\Member->insertMemberRecord(‘chuki10’, ‘Ray’, ‘202020’, ‘raf.yah.s.1@gma…’) #2 {main} thrown in C:\xampp\htdocs\PHP\JAMII-CASH\DataSource.php on line 99

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this Article