PHP Registration Form is the most popular part of web applications. It is commonly used to create a new account on the website with a unique email address or username. Even It stores users’ registration data in the database so that they would be able to login to the website. It is also known as a signup form.
In this tutorial, You will learn to create a simple registration form with complete validation. This form will help the user to quickly signup on to the website and store user data like Name, email, & password in the database using PHP and MYSQL. So, you can integrate it with a login system on your website.
Create a Registration Form Using PHP, MySQL
Before starting coding, you should know the following basic points. These points will give you the best concept to create a registration form using PHP.
- Using PHP, It can take user data and send it through the POST method.
- Using MySQL, It can store the user data into the table of the database.
- It does not allow invalid data and protects from hacking.
- It creates a new account only with a unique email address.
You should also learn the following examples –
1. Create a Registration Form Directory
First of all, Create the following folder structure –
registration-form/ |__database.php |__script.php |__form.php |
2. Create MySQL Database & Table
First of all, Create a MySQL database. You can also create it directly in PHPMyAdmin.
Now, Create a Table in the MySQL database using the following query.
Table Name – users
CREATE TABLE `users` ( `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT, `first_name` varchar(255) DEFAULT NULL, `last_name` varchar(255) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, `created_at` timestamp(6) DEFAULT NULL, )
3. Connect MySQL Database
Now, you have to connect the MYSQL database using the following script.
File Name – database.php
<?php $hostname = "localhost"; // enter your hostname $username = "root"; // enter your table username $password = ""; // enter your password $databasename = "codingstatus"; // enter your database // Create connection $conn = new mysqli($hostname, $username, $password,$databasename); // Check connection if ($conn->connect_error) { die("Unable to Connect database: " . $conn->connect_error); } ?>
4. Create a Registration Form
This HTML document includes a Bootstrap-styled registration form that captures user data. PHP variables display success messages or validation errors, and the form preserves input values for corrections. The form is processed using a separate registration script (script.php
).
File Name – form.php
<?php require('script.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <title>PHP Registration Form</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--bootstrap4 library linked--> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-4"> </div> <div class="col-sm-4"> <!--====registration form====--> <div class="registration-form"> <h4 class="text-center">Create a New Account</h4> <p class="text-success text-center"><?php echo $register; ?></p> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?<" method="post"> <!--//first name//--> <div class="form-group"> <label for="email">First Name</label> <input type="text" class="form-control" placeholder="Enter First Name" name="first_name" value="<?php echo $set_firstName;?>"> <p class="err-msg"> <?php if($fnameErr!=1){ echo $fnameErr; }?> </p> </div> <!--//Last name//--> <div class="form-group"> <label for="email">Last Name</label> <input type="text" class="form-control" placeholder="Enter Last Name" name="last_name" value="<?php echo $set_lastName;?>"> <p class="err-msg"> <?php if($lnameErr!=1){ echo $lnameErr; } ?> </p> </div> <!--// Email//--> <div class="form-group"> <label for="email">Email:</label> <input type="text" class="form-control" id="email" placeholder="Enter email" name="email" value="<?php echo $set_email;?>"> <p class="err-msg"> <?php if($emailErr!=1){ echo $emailErr; } ?> </p> </div> <!--//Password//--> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" class="form-control" placeholder="Enter password" name="password" <p class="err-msg"> <?php if($passErr!=1){ echo $passErr; } ?> </p> </div> <!--//Confirm Password//--> <div class="form-group"> <label for="pwd">Confirm Password:</label> <input type="password" class="form-control" placeholder="Enter Confirm password" name="cpassword"> <p class="err-msg"> <?php if($cpassErr!=1){ echo $cpassErr; } ?> </p> </div> <button type="submit" class="btn btn-danger" name="submit">Register Now</button> </form> </div> </div> <div class="col-sm-4"> </div> </div> </div> </body> </html>
Explanation –
- The PHP script includes a registration script (
script.php
) for form processing. - The HTML document includes Bootstrap libraries for styling and responsiveness.
- The registration form captures user data such as first name, last name, email, password, and confirm password.
- PHP variables are echoed to display success messages or validation errors above the respective form fields.
- The form action is set to the current PHP script (
htmlspecialchars($_SERVER["PHP_SELF"])
) for processing. - Bootstrap styling is applied to create a visually appealing and responsive registration form.
- Input values are preserved after submission to facilitate corrections in case of validation errors.
- The form includes a “Register Now” button with the name attribute set to “submit” for form processing
You can use the following CSS to design the registration form
<style type="text/css"> .registration-form{ background: #f7f7f7; padding: 20px; border: 1px solid orange; margin: 50px 0px; } .err-msg{ color:red; } .registration-form form{ border: 1px solid #e8e8e8; padding: 10px; background: #f3f3f3; } </style>
4. PHP Script to Register user
This PHP script validates and processes a user registration form, ensuring input data integrity, checking for unique email addresses, and inserting validated user data into a database. Success or error messages are displayed accordingly.
File Name – script.php
<?php require_once('database.php'); $db= $conn; // update with your database connection // by default, error messages are empty $register=$valid=$fnameErr=$lnameErr=$emailErr=$passErr=$cpassErr=''; // by default,set input values are empty $set_firstName=$set_lastName=$set_email=''; extract($_POST); if(isset($_POST['submit'])) { //input fields are Validated with regular expression $validName="/^[a-zA-Z ]*$/"; $validEmail="/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/"; $uppercasePassword = "/(?=.*?[A-Z])/"; $lowercasePassword = "/(?=.*?[a-z])/"; $digitPassword = "/(?=.*?[0-9])/"; $spacesPassword = "/^$|\s+/"; $symbolPassword = "/(?=.*?[#?!@$%^&*-])/"; $minEightPassword = "/.{8,}/"; // First Name Validation if(empty($first_name)){ $fnameErr="First Name is Required"; } else if (!preg_match($validName,$first_name)) { $fnameErr="Digits are not allowed"; }else{ $fnameErr=true; } // Last Name Validation if(empty($last_name)){ $lnameErr="Last Name is required"; } else if (!preg_match($validName,$last_name)) { $lnameErr="Digit are not allowed"; } else{ $lnameErr=true; } //Email Address Validation if(empty($email)){ $emailErr="Email is Required"; } else if (!preg_match($validEmail,$email)) { $emailErr="Invalid Email Address"; } else{ $emailErr=true; } // password validation if(empty($password)){ $passErr="Password is Required"; } elseif (!preg_match($uppercasePassword,$password) || !preg_match($lowercasePassword,$password) || !preg_match($digitPassword,$password) || !preg_match($symbolPassword,$password) || !preg_match($minEightPassword,$password) || preg_match($spacesPassword,$password)) { $passErr="Password must be at least one uppercase letter, lowercase letter, digit, a special character with no spaces and minimum 8 length"; } else{ $passErr=true; } // form validation for confirm password if($cpassword!=$password){ $cpassErr="Confirm Password doest Matched"; } else{ $cpassErr=true; } // check all fields are valid or not if($fnameErr==1 && $lnameErr==1 && $emailErr==1 && $passErr==1 && $cpassErr==1) { $firstName =legal_input($first_name); $lastName =legal_input($last_name); $email =legal_input($email); $password =legal_input(md5($password)); // check unique email $checkEmail=unique_email($email); if($checkEmail) { $register=$email." is already exist"; }else{ // Insert data $register=register($firstName,$lastName,$email,$password); } }else{ // set input values is empty until input field is invalid $set_firstName=$first_name; $set_lastName= $last_name; $set_email= $email; } // check all fields are vakid or not } // convert illegal input value to ligal value formate function legal_input($value) { $value = trim($value); $value = stripslashes($value); $value = htmlspecialchars($value); return $value; } function unique_email($email){ global $db; $sql = "SELECT email FROM users WHERE email='".$email."'"; $check = $db->query($sql); if ($check->num_rows > 0) { return true; }else{ return false; } } // function to insert user data into database table function register($firstName,$lastName,$email,$password){ global $db; $sql="INSERT INTO users(first_name,last_name,email,password) VALUES(?,?,?,?)"; $query=$db->prepare($sql); $query->bind_param('ssss',$firstName,$lastName,$email,$password); $exec= $query->execute(); if($exec==true) { return "You are registered successfully"; } else { return "Error: " . $sql . "<br>" .$db->error; } } ?>
Explanation –
- The PHP script includes a database connection and validation functions for a user registration form.
- The script validates input fields (first name, last name, email, password) using regular expressions.
- Unique email validation checks if the provided email already exists in the database.
- If all validations pass, user input values are sanitized, and a registration function inserts the user data into the database.
- Success or error messages are displayed based on the registration result.
- The
legal_input
function trims, strips slashes, and converts special characters to HTML entities for input sanitization. - The
unique_email
function checks if the email is unique in the database. - The
register
function inserts user data into the “users” table and returns success or error messages
What does this statement mean “extract($_POST);”?
Hi john, Thanks for asking your doubt. You have asked a good question.. Read the following point. it will help you to understand..
Its has the simple mean, if you declare
extract($_POST)
then you can get value of input field with its name. you will not need to get value of input field using$_POST['input_field_name']
.suppose that you have an input file with name
mobile_number
like<input type="text" name="mobile_number">
access its value as
$moble_number
.Example –
1. With extract($_POST)
Field Name – first_name –
$first_name
Field Name – last_name –
$last_name
Field Name – email –
$email
Field Name – password –
$password
1. Without extract($_POST)
Field Name – first_name –
$_POST['first_name']
Field Name – last_name –
$_POST['last_name']
Field Name – email –
$_POST['email']
Field Name – password –
$_POST['$password']
I hope.. Now, Your doubt is clear with the above explanation
Thanks a lot.