Build PHP 7 User Registration (Signup) Form with MySQL

Last updated on by Digamber
Learn how to create a basic PHP 7 user registration system, add PHP validation in registration form, securely hash password and store the user information in the MySQL database.

PHP User Registration Form

User registration is an essential process in web development, this process initiates the user account in almost every web applications. User has to login to the web/mobile application using the login credentials.

You can also check out our previous tutorial on Building User Authentication System in PHP and MySQL.

Project Folder and Files

In this tutorial, we will create a simple user registration form using PHP 7 and MySQL and cover the following concepts:

  • Create Registration Form with Bootstrap.
  • Get User Values from HTML form.
  • Implement required validation for the signup form.
  • Check if the user has already registered with the current email id.
  • Securely hash password.
  • Globally manage success and error messages.
  • Store the registration form values in the MySQL database.
\-- php-user-registration
  |-- config
      |--- db.php
  |-- scripts
      |--- register.php
  |-- index.php

Create Database and Table Structure

Use MAMP or XAMPP to create database and a users table inside the database.

Create database `database_name`.

Create `table_name` inside the database.

Use the following SQL script to create users table:

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `firstname` varchar(100) NOT NULL,
  `lastname` varchar(100) NOT NULL,
  `email` varchar(50) NOT NULL,
  `mobile` varchar(20) NOT NULL,
  `password` varchar(255) NOT NULL,
  `date_time` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Build User Form with HTML and Bootstrap

The HTML code creates the user registration form that will allow a user to fill the values through this form. We used the Bootstrap CSS framework that makes the form building faster and mobile-friendly.

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <title>PHP User Registration Form</title>
    <!-- jQuery + Bootstrap JS -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>

<body>

    <div class="container mt-5" style="max-width: 500px">
        <form action="" method="post">
            <h3 class="text-center mb-5">User Registeration Form</h3>
            <div class="form-group">
                <label>First name</label>
                <input type="text" class="form-control" name="firstname" id="firstName" />
            </div>

            <div class="form-group">
                <label>Last name</label>
                <input type="text" class="form-control" name="lastname" id="lastName" />
            </div>

            <div class="form-group">
                <label>Email</label>
                <input type="email" class="form-control" name="email" id="email" />
            </div>

            <div class="form-group">
                <label>Mobile</label>
                <input type="text" class="form-control" name="mobile" id="mobilenumber" />
            </div>

            <div class="form-group">
                <input type="password" class="form-control" name="password" id="password" />
            </div>

            <button type="submit" name="submit" id="submit" class="btn btn-primary btn-lg btn-block">
                Register
            </button>
        </form>
    </div>

</body>

</html>

MySQL Database Configuration

To establish the database connection, place the following code inside the config/database.php file.

<?php

    $hostname = "localhost";
    $username = "phpdemo";
    $password = "4Mu99BhzK8dr4vF1";

    try {
        $connection = new PDO("mysql:host=$hostname;dbname=php_db", $username, $password);
        // set the PDO error mode to exception
        $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        //echo "Database connected successfully";
    } catch(PDOException $e) {
        echo "Database connection failed: " . $e->getMessage();
    }

?>

PHP 7 User Registration Script

Place the following code inside the scripts/register.php.

<?php
   
    // Database connection
    include('config/db.php');
    
    // Error & success messages
    global $success_msg, $email_exist, $emptyError1, $emptyError2, $emptyError3, $emptyError4, $emptyError5;
    

    if(isset($_POST["submit"])) {
        $firstname     = $_POST["firstname"];
        $lastname      = $_POST["lastname"];
        $email         = $_POST["email"];
        $mobile        = $_POST["mobile"];
        $password      = $_POST["password"];

        // verify if email exists
        $emailCheck = $connection->query( "SELECT * FROM users WHERE email = '{$email}' ");
        $rowCount = $emailCheck->fetchColumn();

        // PHP validation
        if(!empty($firstname) && !empty($lastname) && !empty($email) && !empty($mobile) && !empty($password)){
            
            // check if user email already exist
            if($rowCount > 0) {
                $email_exist = '
                    <div class="alert alert-danger" role="alert">
                        User with email already exist!
                    </div>
                ';
            } else {

            // Password hash
            $password_hash = password_hash($password, PASSWORD_BCRYPT);

            $sql = $connection->query("INSERT INTO users (firstname, lastname, email, mobile, password, date_time) 
            VALUES ('{$firstname}', '{$lastname}', '{$email}', '{$mobile}', '{$password_hash}', now())");
            
                if(!$sql){
                    die("MySQL query failed!" . mysqli_error($connection));
                } else {
                    $success_msg = '<div class="alert alert-success">
                        User registered successfully!
                </div>';
                }
            }
        } else {
            if(empty($firstname)){
                $emptyError1 = '<div class="alert alert-danger">
                    First name is required.
                </div>';
            }
            if(empty($lastname)){
                $emptyError2 = '<div class="alert alert-danger">
                    Last name is required.
                </div>';
            }
            if(empty($email)){
                $emptyError3 = '<div class="alert alert-danger">
                    Email is required.
                </div>';
            }
            if(empty($mobile)){
                $emptyError4 = '<div class="alert alert-danger">
                    Mobile number is required.
                </div>';
            }
            if(empty($password)){
                $emptyError5 = '<div class="alert alert-danger">
                    Password is required.
                </div>';
            }            
        }
    }
?>

$_POST method extracts the user’s data when clicked on the submit button.

We are using the SELECT query to find out user email. If the user email already exists then, we will display the message to the user.

The global variable is being used to wrap all the error and success messages that we are using to alert the user for a specific update.

The password_hash method securely hashes the password and store in a long string in the database.

Final User Registration Script Implementation

To make the user form work, include scripts/register.php in the index.php file.

We have to echo the global message variables to display error and success messages.

<?php include('scripts/register.php'); ?>

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <title>PHP User Registration Form</title>
    <!-- jQuery + Bootstrap JS -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>

<body>

    <div class="container mt-5" style="max-width: 500px">
        <form action="" method="post">
            <h3 class="text-center mb-5">User Registeration Form</h3>

            <?php echo $success_msg; ?>
            <?php echo $email_exist; ?>

            <div class="form-group">
                <label>First name</label>
                <input type="text" class="form-control" name="firstname" id="firstName" />

                <?php echo $emptyError1; ?>
            </div>

            <div class="form-group">
                <label>Last name</label>
                <input type="text" class="form-control" name="lastname" id="lastName" />

                <?php echo $emptyError2; ?>
            </div>

            <div class="form-group">
                <label>Email</label>
                <input type="email" class="form-control" name="email" id="email" />

                <?php echo $emptyError3; ?>
            </div>

            <div class="form-group">
                <label>Mobile</label>
                <input type="text" class="form-control" name="mobile" id="mobilenumber" />

                <?php echo $emptyError4; ?>
            </div>

            <div class="form-group">
                <label>Password</label>
                <input type="password" class="form-control" name="password" id="password" />

                <?php echo $emptyError5; ?>
            </div>

            <button type="submit" name="submit" id="submit" class="btn btn-primary btn-lg btn-block">
                Register
            </button>
        </form>
    </div>

</body>

</html>

PHP 7 User Registration Form

Conclusion

We have completed the PHP user registration tutorial. In this tutorial, we have learned how to to create a user form, implement basic validation, securely hash the password, and store the user form values via HTML & PHP form in MySQL database.

You can found the complete code of this tutorial on GitHub.