Creating a Simple Login Using MySQLi Prepared Statement and jQuery

Language

In this tutorial, we will create a Simple Login Using MySQLi Prepared Statement / jQuery. Most of the websites nowadays are required to use MySQLi / PDO statements due to the depreciation of MySQL. This time we will try to work out with MySQLi and Ajax call function to make our simple application more interactive.

Let's start coding!

Creating the Database

First, we will create the database

  • Open the database web server that is already installed from your computer(WAMP, XAMP, etc...)
  • Next, Open the internet browser(Chrome, IE, etc..), and type in the URL address "localhost/PHPMyAdmin"
  • Create your database, and name it "sample"
  • After creating the database, click SQL and paste the code below
  1. CREATE TABLE IF NOT EXISTS `user` (
  2.   `username` varchar(50) NOT NULL,
  3.   `password` varchar(50) NOT NULL
  4.  
  5. INSERT INTO `user` (`user_id`, `username`, `password`) VALUES
  6. (1, 'admin', 'admin');

Creating the Database Connection

After we created the database, we will now create the database connection. To do that, first open any kind of text editor(Notepad++, etc...) that your computer already has. Then, just copy the code below, then name it connect.php

  1. <?php
  2.   $conn = new mysqli('localhost', 'root', '', 'sample');
  3.   if($conn->connect_error){
  4.     die("Fatal Error: Can't connect to database: ". $conn->connect_error);
  5.   }
  6. ?>

Creating the Login Page

Now that the connection is already created, we will now create the HTML form, The HTML form will display the forms that we will be going to use to log in using the accounts of the user. Just copy the code below, then paste it inside the body tag and name it index.php.

  1. <!DOCTYPE html>
  2. <?php
  3.     require 'connect.php';
  4. ?>
  5. <html lang = "eng">
  6.     <head>
  7.         <meta charset = "UTF-8" />
  8.         <style>
  9.             #content{
  10.                 background-color: #ffeecc;
  11.                 width:280px;
  12.                 height:110px;
  13.                 margin: 100px auto;
  14.                 padding:10px;
  15.                 border-radius:2px;
  16.                 -webkit-box-shadow:0px 0px 30px 3px #000;
  17.             }
  18.         </style>
  19.     </head>
  20. <body>
  21.     <center><h2>Creating a Simple Login using Ajax/MySQLi Prepared Statement</h2></center>
  22.     <div id = "content">    
  23.         <form method = "POST">
  24.             <table>
  25.                 <tr>
  26.                     <td><label>Username:</label></td>
  27.                     <td><input type = "text" id = "username"></td>
  28.                 </tr>  
  29.                 <tr>    
  30.                     <td><label>Password:</label></td>
  31.                     <td><input type = "password" id =  "password"></td>
  32.                 </tr>
  33.                 <tr>
  34.                     <td colspan = "2"><br /></td>
  35.                 </tr>
  36.                 <tr>
  37.                     <td colspan = "2"><button type = "button" style = "width:100%;" id = "login">Login</button></td>
  38.                 </tr>
  39.                 <tr>
  40.                     <td colspan = "2"><div id = "result"></div></td>
  41.                 </tr>
  42.             </table>
  43.         </form>
  44.     </div>
  45. </body>
  46. <script src = "jquery-3.1.1.js"></script>
  47. <script src = "login.js"></script>
  48. </html>

jQuery Script

Next, we will now create the jQuery function, just copy the code below and name it "login.js".

  1. $(document).ready(function(){
  2. $error = $('<center><label style = "color:#ff0000;">Invalid username or password</label></center>');
  3. $error2 = $('<center><label style = "color:#ff0000;">User not found!</label></center>');
  4. $success = $('<center><label style = "color:#00ff00;">Successfully login!</label></center>');
  5. $loading = $('<center><img src = "loading.gif" height = "5px" width = "100%"/></center>');
  6.   $('#login').on('click', function(){
  7.     $error.remove();
  8.     $error2.remove();
  9.     $username = $('#username').val();
  10.     $password = $('#password').val();
  11.     if($username == "" && $password == ""){
  12.       $error.appendTo('#result');
  13.     }else{
  14.       $loading.appendTo('#result');
  15.       setTimeout(function(){
  16.       $loading.remove();
  17.       $.post('validator.php', {username: $username, password: $password},
  18.         function(result){
  19.         if(result == "Success"){
  20.           $('#username').val('');
  21.           $('#password').val('');
  22.           $success.appendTo('#result');
  23.           setTimeout(function(){
  24.             $success.remove();
  25.               window.location = 'home.php';
  26.            }, 1000);
  27.               }else{
  28.             $('#username').val('');
  29.             $('#password').val('');
  30.             $error2.appendTo('#result');
  31.           }
  32.             }
  33.           )
  34.         }, 3000);  
  35.           }
  36.       });
  37. });

Creating Credentials Validator

After that we will now create the validator, this script will check if the accounts of the user is existing in the database. Save the file as validator.php

  1. <?php
  2.   require_once 'connect.php';
  3.   $username = $_POST['username'];
  4.   $password = $_POST['password'];
  5.   $stmt = $conn->prepare("SELECT * FROM `user` WHERE username = '$username' && `password` = '$password'") or die(mysqli_error());
  6.   if($stmt->execute()){
  7.     $result = $stmt->get_result();
  8.     $num_rows = $result->num_rows;
  9.   }
  10.   if($num_rows > 0){
  11.     echo "Success";
  12.   }else{
  13.     echo "Error";
  14.   }
  15. ?>

Creating a Simple Home Page

Next, we will now create the home page, just copy the code below"home.php"

  1. <!DOCTYPE html>
  2. <html lang = "eng">
  3.   <head>
  4.     <style>
  5.       #content{
  6.    background-color: #ffeecc;
  7.    width:280px;
  8.     height:110px;
  9.     margin: 100px auto;
  10.     padding:10px;
  11.     border-radius:2px;
  12.     -webkit-box-shadow:0px 0px 30px 3px #000;
  13.      }
  14.     </style>
  15.   </head>
  16. <body>
  17.   <div id = "content">  
  18.     <center><h2>Welcome!</h2></center>
  19.     <center><a href = "index.php" style = "text-decoration:none;">Back</a></center>
  20.   </div>
  21. </body>
  22. </html>

Demo/h3>

There you have it, we created a simple login form. I hope that this tutorial helps you with your projects. For more tutorials and updates, just kindly visit this site.

Enjoy Coding!!!

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Comments

gj mate,helped me a lot...

How can i modify this code to make it usable for multiple users with different roles and having them redirect to pages based on their roles

How could I validate the session? I would like to include a "logout" button. When the user presses that button, the current session will be destroyed and the user will be redirected to index.php. I want to make the following: if I manually type the url "home.php" or if I press the back button after I pressed on logout, make the script that will redirect me to "index.php" so only authenticated users can access "home.php". What do I need to edit in order to make this work? I'm a newbie to all of this.

Add new comment