Simple login form in PHP and MySQL

Login and Registration is very common section in almost all websites. So this is very basic post in which i am going to show you how the login and registration process works. This is a Simple login form in PHP and mysql. In this script, a form will be displayed with two fields, username and password. When user is submitting with valid user name and password, then he can access authenticated page. Other wise user again has to fill in the form. We have very cool design as well you can just download form link down below. This is how it will look like:

 

Simple login form in PHP

It’s time  to create login system so let’s follow these steps:

1. Create a Database

The very first step is database creation. We will use following query to create database:

CREATE DATABASE demo;

Note: demo is name of database you can change it with any name.

2.  Create a Database Table

Now we need table in database so we can store information about user like email,password etc. Let’s run following command to create table in database:

CREATE TABLE users
(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(30) UNIQUE,
pass VARCHAR(50),
email VARCHAR(70) UNIQUE
);

Simple login form in PHP

You can see it will create table in demo database something like in image above.

 

3. Connect to MySql Database with PHP

After create the database now its time to use this into PHP project. So let’s create PHP file with name db_config.php. In this file we will create connection between database and application.

define('DB_SERVER', 'localhost');   // this is the server name
define('DB_USERNAME', 'root'); //this is username for database by default its root
define('DB_PASSWORD', ''); // this is password for database i.e empty by default
define('DB_DATABASE', 'demo'); //this is database name which we have create just now

 

4. Define common methods in class

Now create a class.php  file where we will declare classes so we can easily access on other PHP pages. Creating classes is best practice in php otherwise we can also directly use query on all pages but that is not what I like most :p


<?php
include "db_config.php";

class User

{
public $db;

public

function __construct()
{
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_errno())
{
echo "Error: Could not connect to database.";
exit;
}
}

/* Registration process */
public

function reg_user($username, $password, $email)
{
$password = md5($password);
echo $sql = "SELECT * FROM users WHERE name='$username' OR email='$email'";

// checking if the username or email is available in db

$check = $this->db->query($sql);
$count_row = $check->num_rows;

// if the username is not in db then insert to the table

if ($count_row == 0)
{
echo $sql1 = "INSERT INTO users SET name='$username', pass='$password', email='$email'";
exit;

// $result = mysqli_query($this->db,$sql1) or die(mysqli_connect_errno()."Data cannot inserted");
// return $result;

}
else
{ //return false;}
}

/*Login Process */
public

function check_login($emailusername, $password)
{
$password = md5($password);
$sql2 = "SELECT id from users WHERE email='$emailusername' or name='$emailusername' and pass='$password'";

// checking if the username is available in the table

$result = mysqli_query($this->db, $sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1)
{

// this login var will use for the session thing

$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
return true;
}
else
{
return false;
}
}

/*Showing the Username or Fullname ***/
public

function get_username($uid)
{
$sql3 = "SELECT name FROM users WHERE id = $uid";
$result = mysqli_query($this->db, $sql3);
$user_data = mysqli_fetch_array($result);
echo $user_data['name'];
}

/*Start the session */
public

function get_session()
{
return $_SESSION['login'];
}

/*Destroy the session */
public

function user_logout()
{
$_SESSION['login'] = FALSE;
session_destroy();
}
}

?>

 

 

 

As you can see we have different functions for login, register, logout etc. As we are using classes so we can just include this file in any PHP file and we can access these functions. You can read more about PHP Classes here.

5. Create html login form and perform login

 

This is final step and we will have ready php login system. Now create index.php page where we will create  functions for login and register. Also we will include class.php file to access  functions which we have defined before. In index.php file add following php code:

<?php
session_start();
include_once 'include/class.php';
$user = new User();

if (isset($_REQUEST['submit'])) {
extract($_REQUEST);
$login = $user->check_login($emailusername, $password);
if ($login) {
// Registration Success
header("location:home");
} else {
// Registration Failed
echo 'Wrong username or password';
}
}

if (isset($_REQUEST['register'])) {
extract($_REQUEST);
$register = $user->reg_user($username, $password, $email);
if ($register) {
// Registration Success
echo '<center>Registration successful. Please enter detail for login.<center>';
} else {
// Registration Failed
echo 'Registration failed. Email or Username already exits please try again';
}
}
?>

Now let’s add some html in index.php file:-


<div class="container">
<div class="tab-container">
<a href="javascript:;" id="signup">Signup</a>
<a href="javascript:;" class="active" id="login">Login</a>
</div>
<div class="box-container">
<div class="login">
<div class="login-section">
<h1>Please Login</h1>
<form action="" method="post" name="login">
<input type="text" id="username" placeholder="UserName or Email" name="emailusername" value="" required="">
<input type="password" id="password" placeholder="Password" name="password" value="" required="">
<input onclick="return(submitlogin());" type="submit" name="submit" value="Login" />
</form>
</div>
</div>

<div class="signup">
<div class="login-section">
<h1>Create new Account</h1>
<form action="" method="post" name="reg">
<input type="text" id="username" name="username" placeholder="Username" value="" required="">
<input type="text" id="email" name="email" placeholder="Email" value="" required="">
<input type="password" id="password" name="password" placeholder="Password" value="" required="">
<input onclick="return(submitreg());" type="submit" name="register" value="Register" />
</form>
</div>
</div>
</div>
</div>

We are using some jQuery as well so we need to add this code as well to just hide/show login or register section :

 


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script>
$(function(){
$('.tab-container a').click(function(){

var id=$(this).attr('id');

var el=$('.'+id);

var self=$(this);

if(!$(self).hasClass('active')){

var apanel=$('.'+$('.active').attr('id'));
apanel.fadeOut('fast',function(){
el.show();

$(self).parent().find('a').removeClass('active');
$(self).addClass('active');
});
}
});
});
</script>

<script type="text/javascript" language="javascript">

function submitlogin() {
var form = document.login;
if(form.emailusername.value == ""){
alert( "Enter email or username." );
return false;
}
else if(form.password.value == ""){
alert( "Enter password." );
return false;
}
}
function submitreg() {
var form = document.reg;

if(form.username.value == ""){
alert( "Enter username." );
return false;
}
else if(form.password.value == ""){
alert( "Enter password." );
return false;
}
else if(form.email.value == ""){
alert( "Enter email." );
return false;
}
}

</script>

Simple login form in PHP

 

You can check live demo here

Or Download Source Code

Total Views (1583)

2 Comments

  1. buy rs gp May 8, 2017 Reply

Add a Comment

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