Registration and Login Form in PHP and MySQL

This is the most important and common task while creating a web application. In this post you will learn to create a Registration and Login Form in PHP and MySQL. All you need to do is follow these simple steps.

Step 1- Create User table in MySQL

The first step to create a Registration and Login Form in PHP and MySQL is to open Localhost/PHPMYADMIN and create a database. We have created the database named RegisterDB for this task. You can keep this name or create table in an existing database in your MySQL dashboard.

You can create the table using the GUI of MySQL for creating a new table. Or you can copy this “CREATE TABLE” statement and paste it in the SQL tab of your MySQL Database. Click “Go” button to create the table

CREATE TABLE `users` (
  `UserID` int(11) NOT NULL,
  `UserName` varchar(50) DEFAULT NULL,
  `UserEmail` varchar(100) NOT NULL,
  `Password` varchar(50) NOT NULL,
  `CreatedOn` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) 

ALTER TABLE `users`
  ADD PRIMARY KEY (`UserID`),
  ADD UNIQUE KEY `UserName` (`UserName`);

Step2- Create Registration and Login Form in PHP and MySQL

A PHP application is always run on server. This application must be created in the XAMPP/WAMP/LAMP folder in your computer so that you can access it through Localhost. If you are using XAMPP create Registration folder under c:\XAMPP\HTDOCS and save the two php files here that we are going to create in step 2 and step 3.

The login page is the index.php file for this assignment. It contains a textbox to let a user enter his previously registered user name. The second is a password field where user can enter his password. On clicking the Login button the username and password will be authenticated with data in table.  

Registration and Login Form in PHP and MySQL
<HTML>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<BODY>

<div class="container">
<div style="width: 1100px;  border-width: 1px; height:150px; text-align:center; background-color:rgba(7, 109, 175, 0.5)"><h2 style="padding-top:50px">Login</h2></div>
<div style="width: 1100px;  border-width: 1px; height:30px; text-align:center; background-color:rgb(7, 109, 175)"></div>
<div style="padding:50px; margin-top:50px; border-style: solid; border-width: 1px; align:center; display: block; margin-left: auto; margin-right:auto; width: 60%;color:rgb(7, 109, 175);">

<?php
// check is submit button is clicked by user
	if (isset($_POST['submit']))
	{
			// check if user name and password are entered
			if (!empty($_POST['UserName']) and !empty($_POST['password']) )
			{
			//if user name and password are entered connect with database
			$con=mysqli_connect("localhost","root","","registerDB");
			// get values entered by user using POST Superglobal
			$uname=$_POST['UserName'];
			$pwd=$_POST['password'];
			//create SQL statement to get passord stored in table for the user name entered
			$qry="Select Password from users where UserName='$uname'";
			//run quary
			$res=mysqli_query($con,$qry);

			while ($row=mysqli_fetch_array($res))
			{
				// store password from table into a variable
				$userpwd=$row[0];
			}
				//check if password enetered by user matches with that stored in users table
				if ($pwd==$userpwd) 
				{
						// Success message
						echo "<script> alert('Login Successful');</script>";
						/*session_start(); use this for opening the dashboard for user and store session variable
						$_SESSION['Uname']=$uname;
						header('refresh:0;url=Dashboard.php');*/
						header('refresh:0;url=index.php');
				}
				else
				{
					// if  credentials are incorrect
					echo '<script> alert("Incorrect UserName/Password");</script>';
					header('refresh:0;url=index.php');
				}
			
			}
			else
			{
				// if  fields are left empty
				echo "<script>alert('User Name and Password cannot be left empty');</script>";
				header('refresh:0;url=index.php');
			}
	}
	else
// Display the login form using heredoc statement
	{
$str=<<<_LBL
<div class="container">
<div class="row">
    
	<div class="col">
	<form method="post" action="index.php">
	<input type="Name" class="form-control" id="exampleInputName" name="UserName" placeholder="Enter User Name"><BR>
	<input type="password" class="form-control" id="exampleInputpassword1" name="password" placeholder="Enter password"><br>
	<button class="btn btn-success"  name="submit" id="exampleSubmit" value="Login" style="border-color:rgb(7, 109, 175);background-color:rgb(7, 109, 175)">Login</button>
	<a href="register.php"><button class="btn btn-success"  type="button" id="exampleSubmit" value="Register" style="border-color:rgb(7, 109, 175);background-color:rgb(7, 109, 175)">Register as New User</button></a>
	</form>
</div>
</div>
</div>
_LBL;
echo $str;
}
?>
</diV> 
<BODY>
<HTML>

If credentials are incorrect a message “Incorrect User Name/ Password” is flashed.

Login Form Error

If the credentials match with that in the users table the message is displayed “Login Successful “

Login Form Success

A second button “Register as New User” opens a registration form so that user can enter his details to get registered in your web application.

Create  the login.php file with the following code. It is designed using BootStrap CSS available here

Step2-Create and Code Registration Form

In this PHP form the user can enter a user name with which the user wants to login in future sessions. Other required fields are email id and password. The user is asked to enter the password twice to confirm it.

User Registration and Login Form in PHP and MySQL
<HTML>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<BODY>

<div class="container">
<div style="width: 1100px;  border-width: 1px; height:150px; text-align:center; background-color:rgba(7, 109, 175, 0.5)"><h2 style="padding-top:50px">User Registration</h2></div>
<div style="width: 1100px;  border-width: 1px; height:30px; text-align:center; background-color:rgb(7, 109, 175)"></div>
<div style="padding:50px; margin-top:50px; border-style: solid; border-width: 1px; align:center; display: block; margin-left: auto; margin-right:auto; width: 60%;color:rgb(7, 109, 175);">

<?php
// check if the fields are non empty
if (!empty($_POST['UserName']) and !empty($_POST['password']) and !empty($_POST['email']))
{
// if fields are non empty proceed to connect with database 	
$con=mysqli_connect("localhost","root","","registerdb");
// get values entered by a user using POST superglobal 
$uname=$_POST['UserName'];
$pwd=$_POST['password'];
$cpwd=$_POST['ConfirmPassword'];
$email=$_POST['email'];
// Check if password and confirm password match
If ($pwd== $cpwd)
{
//If everything is OK create query to insert details of new user int table
$qry1="insert into Users (UserName,Password,UserEmail) values('$uname','$pwd','$email')";
//Execute query 
$res1=mysqli_query($con,$qry1);
//check for success
if (mysqli_affected_rows($con)>0)
{
	// success message
	echo "<script>alert('User Details Saved');</script>";
	header('refresh:0;url=index.php');
	unset($qry1);
}
else
{	
	//duplicate user name message. 1062 is mysqli error number for violation of unique constraint
	if (mysqli_errno($con)==1062)
	{	
			echo "<script>alert('User name existing!! Enter a different User Name');</script>";
			header('refresh:0;url=register.php');
	}
}
}
else
{
	//message mismatch message
	echo "<script>alert('Passwords do not match');</script>";
	header('refresh:0;url=register.php');
	unset($qry1);
}
}
elseif (isset($_POST['submit']))
{
	// check if fields are empty
	echo "<script>alert('User Name, Password and Email cannot be left empty');</script>";
	header('refresh:0;url=register.php');
}
else
// display the Registration form using the HTML code for form using heredoc syntax
{
$str=<<<_LBL
<div class="container">
<div class="row">
    
	<div class="col">
	<form method="post" action="Register.php">
	<input type="Name" class="form-control" id="exampleInputName" name="UserName" placeholder="Enter User Name"><BR>
	<input type="email" class="form-control" id="exampleInputEmail1" name="email" placeholder="Enter your email"><BR>
	<input type="password" class="form-control" id="exampleInputpassword1" name="password" placeholder="Enter password"><br>
	<input type="password" class="form-control" id="exampleInputpassword1" name="ConfirmPassword" placeholder="Confirm password"><br>
	<button class="btn btn-success"  name="submit" id="exampleSubmit" value="Submit" style="border-color:rgb(7, 109, 175);background-color:rgb(7, 109, 175)">Submit</button>
	</form>
</div>
</div>
</div>
_LBL;
echo $str;
}

?>
</DiV> 
<BODY>

In both PHP files we have used heredoc syntax to add the HTML part for form designing.

User Registration Success

Three validations for registration form are implemented

  • If the two passwords do not match, message is displayed to user that the passwords do not match.
User Registration mismatch password
  • If any of these fields- username, password or email are left blank, data will not be saved into table and message is displayed. 
User Registration Empty Fields Validation
  • If a user enters a duplicate user name, message will be flashed to user to enter a unique user name.
User Registration Duplicate

As you have created Registration and Login Form in PHP and MySQL with us, you must have realized that it is very easy to implement. We would love to read your suggestions.

Be First to Comment

Leave a Reply

Your email address will not be published.