User registration is a very useful feature and it comes almost with every website, social media, and shopping cart or even with a blog. User registration distinguishes information between registered or unregistered users.
So in this tutorial we are going to create user registration form with jquery and PHP validation and save user registration form data into mysql table.
How User Registration in PHP works:
- Get data from user using input fields (First Name, Last Name, Email, Phone and Password).
- Perform basic validation using PHP.
- Check user duplication.
- Save in Mysql Database.
This is the basic user registration in PHP. Therefore I will focus on the basic functionality of user registration. I will only use some basic jQuery form validation and basic PHP form validation functions. Now let’s start.
Create Database:
1 2 3 4 |
Create database demo; Use demo; |
Create Table:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
CREATE TABLE `users` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `first_name` VARCHAR(255) NULL DEFAULT NULL, `last_name` VARCHAR(255) NULL DEFAULT NULL, `email` VARCHAR(255) NULL DEFAULT NULL, `phone` VARCHAR(255) NOT NULL, `password` VARCHAR(255) NULL DEFAULT NULL, `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB AUTO_INCREMENT=6 ; |
Database Connection:
config.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php $host = "localhost"; $userName = "root"; $password = ""; $dbName = "demo"; // Create database connection $conn = mysqli_connect($host, $userName, $password, $dbName); // Check connection if(!$conn) { die("Connection failed: " . mysqli_connect_error()); } ?> |
Registration Form HTML:
Index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<div class="container"> <h3 class="heading">Registration Form</h3> <?php if(isset($errorMsg)) { echo '<div class="error_msg">'; echo $errorMsg; echo '</div>'; unset($errorMsg); } if(isset($successMsg)) { echo '<div class="success_msg">'; echo $successMsg; echo '</div>'; unset($successMsg); } ?> <div class="form-cont"> <form name="myForm" id="registrationForm" method="POST" action="<?php echo $_SERVER['PHP_SELF']?>"> <label for="firstName">First Name</label> <input type="text" name="first_name" placeholder="Type your First Name" id="firstName"/> <label for="lastName">Last Name</label> <input type="text" name="last_name" placeholder="Type your Last Name" id="lastName"/> <label for="emailAddress" >Email</label> <input type="text" name="email" placeholder="Type your Email" id="emailAddress"/> <label for="phone" >Phone</label> <input type="text" name="phone" placeholder="Type your Email" id="phone"/> <label for="password">Password</label> <input type="password" name="password" placeholder="Type your Password" id="password"/> <input type="submit" id="submitForm" value="Submit" name="submit"/> </form> </div> </div> |
Above is the HTML form with 5 input fields. Form method attribute has POST value which means form data will not be appear in URL (always use post method for secure information like password). Action attribute has $_SERVER['PHP_SELF']
which means form will be submitted on the same page.
$errorMsg
and $successMsg
variables are used to display error and success messages.
Style.css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
body{ font-family:verdana; } .container{ width:320px; margin:0 auto; margin-top:100px; padding:10px; border-radius:4px; -webkit-box-shadow: -1px 0px 21px -8px rgba(0,0,0,0.75); -moz-box-shadow: -1px 0px 21px -8px rgba(0,0,0,0.75); box-shadow: -1px 0px 21px -8px rgba(0,0,0,0.75); } .heading{ font-size:26px; line-height:28px; margin:0px 0px 15px 0px; color: #4387fd; } label{ font-size:14px; margin:10px 0px 3px 0px; display:block; font-weight:600; } .form-cont input[type=text], .form-cont input[type=password]{ display:block; height:30px; width:300px; margin-bottom:8px; border:1px solid #eeeeee; border-radius:2px; padding-left:2px; } .form-cont input[type=submit]{ background:#4387fd; color:#ffffff; border:1px solid #4387fd; height:30px; } .form-cont input[type=submit]:hover{ box-shadow:0 1px 0 rgba(0,0,0,0.30); } .disable-btn{ background:red !important; color:#ffffff !important; border:1px solid red !important; height:30px !important; } .success_msg{ font-size:14px; background:#34d58e; border:1px solid #34d58e; font-size:12px; margin:5px 0 5px 0; padding:3px; color:#ffffff; } .error_msg{ background:#EE5A5B; border:1px solid #ee0000; font-size:12px; margin:5px 0 5px 0; padding:3px; color:#ffffff; } |
jQuery Validation File
Script.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 |
function checkFirstNameEmpty(inputID) { $(inputID).blur(function(){ if($(this).val() == '') { $(this).css('border','1px solid red'); } else { $(this).css('border','1px solid green'); } }); } function checkLastNameEmpty(inputID) { $(inputID).blur(function(){ if($(this).val() == '') { $(this).css('border','1px solid red'); } else { $(this).css('border','1px solid green'); } }); } function checkPasswordEmpty(inputID) { $(inputID).blur(function(){ if($(this).val() == '') { $(this).css('border','1px solid red'); } else { $(this).css('border','1px solid green'); } }); } //regex to validate email function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } // validation for email input using validateEmail Function function checkValidEmail(emailInputID) { $(emailInputID).blur(function(){ var email = $(emailInputID).val(); if (validateEmail(email)) { $(this).css('border','1px solid green'); } else { $(this).css('border','1px solid red'); } }); } // regex to validate phone function validatePhone(inputtxt) { //+XX-XXXX-XXXX //+XX.XXXX.XXXX //+XX XXXX XXXX var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/; if(inputtxt.match(phoneno)) { return true; } else { return false; } } // validation for phone input using validatePhone Function function checkvalidPhoneNumber(phoneInputID) { $(phoneInputID).blur(function(){ var phone = $(phoneInputID).val(); var getPhone = validatePhone(phone); if(getPhone) { $(this).css('border','1px solid green'); } else { $(this).css('border','1px solid red'); } }); } $(document).ready(function(){ //run time form validation checkFirstNameEmpty("#firstName"); checkLastNameEmpty("#lastName"); checkValidEmail("#emailAddress"); checkvalidPhoneNumber("#phone"); checkPasswordEmpty("#password"); //when click on submit $("#submitForm").click(function(e){ if($("#firstName").val() == '') { $("#firstName").css('border','1px solid red'); return false; } if($("#lastName").val() == '') { $("#lastName").css('border','1px solid red'); return false; } if($("#emailAddress").val() == '') { $("#emailAddress").css('border','1px solid red'); return false; } if($("#emailAddress").val() != '') { var email = $("#emailAddress").val(); if (!validateEmail(email)) { return false; } } if($("#phone").val() == '') { $("#phone").css('border','1px solid red'); return false; } if($("#phone").val() != '') { var getPhone = validatePhone($("#phone").val()); if(!getPhone) { return false; } } if($("#password").val() == '') { $("#password").css('border','1px solid red'); return false; } }); }); |
In scripts.js
there are 5 main functions which will trigger on blur event to verify each field separately. validateEmail
function will validate email via regex and validatePhone
function will validate phone number in 3 format that are +XX-XXXX-XXXX, +XX.XXXX.XXXX, +XX XXXX XXXX. You can use any phone number regex in var phoneno
. I also added blank input validation when the form will submit.
PHP Registration Form after Submit:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
if(isset($_POST['submit'])) { $firstName = htmlentities(trim($_POST['first_name']),ENT_QUOTES); $lastName = htmlentities(trim($_POST['last_name']),ENT_QUOTES); $email = htmlentities(trim($_POST['email']),ENT_QUOTES); $phone = htmlentities(trim($_POST['phone']),ENT_QUOTES); $password = htmlentities(trim($_POST['password']),ENT_QUOTES); if(!empty($firstName) && !empty($lastName) && !empty($email) && !empty($phone) && !empty($password)) { $sql = "select * from users where email = '".$email."'"; $result = mysqli_query($conn, $sql); $numRows = mysqli_num_rows($result); if($numRows == 0) { $options = array("cost"=>4); $hashPassword = password_hash($password,PASSWORD_BCRYPT,$options); $sqlInsert = "insert into users (first_name, last_name, email, phone, password) values('".$firstName."', '".$lastName."' , '".$email."', '".$phone."', '".$hashPassword."')"; $rs = mysqli_query($conn, $sqlInsert); if($rs) { $successMsg = "Form has been saved successfully"; } else { $errorMsg = "Unable to save user. Please try again"; } } else { $errorMsg = "User already exist"; } } else { $errorMsg = 'All fields are required'; } } |
trim
function is used to remove extra spaces and htmlentities
convert characters to html entities. In registration form all fields are required. If any field will come up with blank data then we will through error in $errorMsg
. $sql
is used to check duplicate email in the database. If $sql
query will return 0 record then I will insert data into mysql table otherwise I will through error. $hashPassword
is using password_hash function which creates password hash.
All Code Together:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
<?php require_once("config.php"); if(isset($_POST['submit'])) { $firstName = htmlentities(trim($_POST['first_name']),ENT_QUOTES); $lastName = htmlentities(trim($_POST['last_name']),ENT_QUOTES); $email = htmlentities(trim($_POST['email']),ENT_QUOTES); $phone = htmlentities(trim($_POST['phone']),ENT_QUOTES); $password = htmlentities(trim($_POST['password']),ENT_QUOTES); if(!empty($firstName) && !empty($lastName) && !empty($email) && !empty($phone) && !empty($password)) { $sql = "select * from users where email = '".$email."'"; $result = mysqli_query($conn, $sql); $numRows = mysqli_num_rows($result); if($numRows == 0) { $options = array("cost"=>4); $hashPassword = password_hash($password,PASSWORD_BCRYPT,$options); $sqlInsert = "insert into users (first_name, last_name, email, phone, password) values('".$firstName."', '".$lastName."' , '".$email."', '".$phone."', '".$hashPassword."')"; $rs = mysqli_query($conn, $sqlInsert); if($rs) { $successMsg = "Form has been saved successfully"; } else { $errorMsg = "Unable to save user. Please try again"; } } else { $errorMsg = "User already exist"; } } else { $errorMsg = 'All fields are required'; } } ?> <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <h3 class="heading">Registration Form</h3> <?php if(isset($errorMsg)) { echo '<div class="error_msg">'; echo $errorMsg; echo '</div>'; unset($errorMsg); } if(isset($successMsg)) { echo '<div class="success_msg">'; echo $successMsg; echo '</div>'; unset($successMsg); } ?> <div class="form-cont"> <form name="myForm" id="registrationForm" method="POST" action="<?php echo $_SERVER['PHP_SELF']?>"> <label for="firstName">First Name</label> <input type="text" name="first_name" placeholder="Type your First Name" id="firstName"/> <label for="lastName">Last Name</label> <input type="text" name="last_name" placeholder="Type your Last Name" id="lastName"/> <label for="emailAddress" >Email</label> <input type="text" name="email" placeholder="Type your Email" id="emailAddress"/> <label for="phone" >Phone</label> <input type="text" name="phone" placeholder="Type your Email" id="phone"/> <label for="password">Password</label> <input type="password" name="password" placeholder="Type your Password" id="password"/> <input type="submit" id="submitForm" value="Submit" name="submit"/> </form> </div> </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src="script.js"></script> </body> </html> |