Follow

Welcome to TechYari!

Tutorials on webdesign, web development and more...
Today I am going to discuss live username availability check in php with ajax, an approach used by many websites on there registration form. This code is an example of how you can check availability of a username while user type in the forms input field. In order to keep it simple I have left the registration part.

I am using PHP with jQuery and Ajax but same can be achieved in any programming language with the ajax call provided in the tutorial.

live-username-availability-check-in-php-with-ajax


Download Source Live Demo


Database table setup


First we will create a table to store our users. You can use you own database/table and change the configuration and query in next step to point to that instead of creating this dummy db table.


CREATE TABLE demo_users(
   id INT NOT NULL AUTO_INCREMENT,
   username VARCHAR(100) NOT NULL,
   PRIMARY KEY (id)
);

Configure PHP to connect to database(database-config.php)


Here we configure database related details. Change the variable values according to your environment


<?php
   // define database related variables
   $database = 'techyari_demos';
   $host = 'localhost';
   $user = 'root';
   $pass = '';

   // try to conncet to database
   $dbh = new PDO("mysql:dbname={$database};host={$host};port={3306}", $user, $pass);

   if(!$dbh){

      echo "unable to connect to database";
   }
   
?>

Registration Page (index.php)


Here we use oninput event on username input field to trigger our javascript function which will get username and pass it to check.php file via ajax using jquery. I am leaving out other parts of code which are not related to the tutorial, be sure to include jQuery and main.js file in index.php. You can download souce code if you have any doubts.


<h4>Choose a username</h4><br/>
                                  <input type="text" name="username" class="col-md-8 " id="username" placeholder="Type here" required autofocus oninput="checkname()">
                                  <span class="col-md-4" id="checking"></span>

Checking the username availability in database with PHP (check.php)


This script fires a query to database with the name entered by user and returns appropriate message to the ajax function. See next step for ajax call.



<?php 
 require 'database-config.php';

 $username = "";
 
 if(isset($_GET['username'])){
  $username = $_GET['username'];
 }
 
 $q = 'SELECT * FROM demo_users WHERE username LIKE :username';

 $query = $dbh->prepare($q);

 $query->execute(array(':username' => $username));

 if($query->rowCount() == 0){
  echo "Available";
 }else{
  echo "Username not available";
 }


?>

Making request to check username via Ajax with jQuery (main.js)


We will call check.php via ajax and display the appropriate results to the user.


var username = "";
var checkname = function(){
     var username = $("#username").val();
     $('#checking').html("");
  if(username!=""){
   $('#checking').html("<p>Checking....</p>");
   $.ajax({
       url: "check.php",
       type: 'GET',
       data: {username : username},
       success: function(data) {  
        $('#checking').html("");
   if(data=="Available"){
    
    $('#checking').html('<p class="bg-success">Available</p>');
   }else{
    
    $('#checking').html('<p class="bg-danger">Not available</p>');
   }
   },
      error: function(e) {
     $('#checking').html('<p class="bg-danger">There was an error</p>');
  }
 });

 }
}


That's all we have created a simple mechanism to check username availability with ajax. Feel free to post your suggestions and queries.
Login and logout functionality is crucial to any web application. Today I am going to discuss a role based login system in PHP with MySql database. We will have two login roles. One as admin login and another as user login. When logged in users with admin role will be redirected to admin home page whereas users with user role will be redirected to user home page. I am creating two different pages to make it simple however same strategy can be used to show/hide links based on logged in roles as well.



User Table Setup


To manage users with both the login roles create a database and setup user table and insert at least two rows. one with admin user role and another with user role.


// setup messages table
CREATE TABLE users(
   id INT NOT NULL AUTO_INCREMENT,
   username VARCHAR(100) NOT NULL,
   password VARCHAR(100) NOT NULL,
   role VARCHAR(100) NOT NULL,
   PRIMARY KEY (id)
);


Database Configuration (database-config.php)


Use below code to configure database connection with the database table created in earlier step. Change variable values according to your database environment.


<?php
   // define database related variables
   $database = 'techyari_demos';
   $host = 'localhost';
   $user = 'root';
   $pass = '';

   // try to conncet to database
   $dbh = new PDO("mysql:dbname={$database};host={$host};port={3306}", $user, $pass);

   if(!$dbh){

      echo "unable to connect to database";
   }
   
?>

Login Page (index.php)


Login page contains the login form which points to authenticate.php file when user clicks on login button. In authenticate.php file we receive the user input via $_POST variables and validate the user login credentials.


  <div class="col-md-6 col-md-offset-3">
                    <h4></span>Log in with your credentials<span class="glyphicon glyphicon-user"></h4><br/>
                            <div class="block-margin-top">
                              <?php 

                                $errors = array(
                                    1=>"Invalid user name or password, Try again",
                                    2=>"Please login to access this area"
                                  );

                                $error_id = isset($_GET['err']) ? (int)$_GET['err'] : 0;

                                if ($error_id == 1) {
                                        echo '<p class="text-danger">'.$errors[$error_id].'</p>';
                                    }elseif ($error_id == 2) {
                                        echo '<p class="text-danger">'.$errors[$error_id].'</p>';
                                    }
                               ?>  

                              <form action="authenticate.php" method="POST" class="form-signin col-md-8 col-md-offset-2" role="form">  
                                  <input type="text" name="username" class="form-control" placeholder="Username" required autofocus><br/>
                                  <input type="password" name="password" class="form-control" placeholder="Password" required><br/>
                                  <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
                             </form>
                           </div>
            </div>

Authentication (authenticate.php)


This file takes care of authentication, it also requires database-config.php file to connect to database.


<?php 
 require 'database-config.php';

 session_start();

 $username = "";
 $password = "";
 
 if(isset($_POST['username'])){
  $username = $_POST['username'];
 }
 if (isset($_POST['password'])) {
  $password = $_POST['password'];

 }
 

 $q = 'SELECT * FROM users WHERE username=:username AND password=:password';

 $query = $dbh->prepare($q);

 $query->execute(array(':username' => $username, ':password' => $password));


 if($query->rowCount() == 0){
  header('Location: index.php?err=1');
 }else{

  $row = $query->fetch(PDO::FETCH_ASSOC);

  session_regenerate_id();
  $_SESSION['sess_user_id'] = $row['id'];
  $_SESSION['sess_username'] = $row['username'];
        $_SESSION['sess_userrole'] = $row['role'];

        echo $_SESSION['sess_userrole'];
  session_write_close();

  if( $_SESSION['sess_userrole'] == "admin"){
   header('Location: adminhome.php');
  }else{
   header('Location: userhome.php');
  }
  
  
 }


?>

Admin Home Page (adminhome.php)


On validation if a user is admin he is redirected to this page. We have included a piece of code on top of the page to check if session exists and the user accessing the page has admin rights. If not the user will be redirected back to login (index) page with proper error messages.


<?php 
    session_start();
    $role = $_SESSION['sess_userrole'];
    if(!isset($_SESSION['sess_username']) || $role!="admin"){
      header('Location: index.php?err=2');
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    
    <div class="navbar navbar-default navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="http://techyari.in">Techyari.in</a>
        </div>

        <div class="navbar-collapse collapse">
          <ul class="nav navbar-nav navbar-right">
            <li><a href="#"><?php echo $_SESSION['sess_username'];?></a></li>
            <li><a href="logout.php">Logout</a></li>
          </ul>
        </div>
      </div>
    </div>

    <div class="container homepage">
      <div class="row">
         <div class="col-md-3"></div>
            <div class="col-md-6 welcome-page">
              <h2>This is Admin area.</h2>
            </div>
          <div class="col-md-3"></div>
        </div>
    </div>    

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
    </body>
</html>


User Home Page (userhome.php)


This is for normal users, functionality is same as admin page


<?php 
    session_start();
    $role = $_SESSION['sess_userrole'];
    if(!isset($_SESSION['sess_username']) || $role!="user"){
      header('Location: index.php?err=2');
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    
    <div class="navbar navbar-default navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="http://techyari.in">Techyari.in</a>
        </div>

        <div class="navbar-collapse collapse">
          <ul class="nav navbar-nav navbar-right">
            <li><a href="#"><?php echo $_SESSION['sess_username'];?></a></li>
            <li><a href="logout.php">Logout</a></li>
          </ul>
        </div>
      </div>
    </div>

    <div class="container homepage">
      <div class="row">
         <div class="col-md-3"></div>
            <div class="col-md-6 welcome-page">
              <h2>This is User area.</h2>
            </div>
          <div class="col-md-3"></div>
        </div>
    </div>    

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
    </body>
</html>


Session Management (logout.php)


Session management is crucial for our login system to work properly, this page takes care of logout functionality (destroys session variables on logout)


<?php 
 session_start();
 session_destroy();
 header('Location: index.php');
?>

A bit of Styling (style.css)



h2{padding: 10px;}
.homepage{margin-top: 50px; text-align: center;}
th,td{border: 1px solid gray;padding:5px;}

That's all we have built a simple yet powefull login sytem that supports multiple user roles. If you get into any trouble you can download the source code here Share your thoughts below using comment box.
In this tutorial I am going to create a simple pagination script in PHP. This tutorial does not require any use of JavaScript or jQuery. It is based on pure PHP. I have used MySql as database but you can use any database that you like. I am writing this tutorial for PHP  as it is  used by more then 75 % of the websites. I have used twitter bootstrap for look and feel and therefor have added jQuery, you may use anything that suits you.

The pagination script will have following features :
  • Numbered links based on total messages in database table.
  • Next and Previous links based on the page.


Pgination in PHP with MySql database


Database Table Setup (table-setup.php)

Below is code to setup a table with two columns id & message. Create a database in MySql and run query given below to setup messages table. Now you need to populate this table with some data at least 20 rows so that we can get a nice feel of pagination.


CREATE TABLE messages(
   id INT NOT NULL AUTO_INCREMENT,
   message VARCHAR(100) NOT NULL,
   PRIMARY KEY (id)
);


Database Connection Setup (database-config.php)

To connect to database via php use below code. Change variable values according to your database environment.


<?php
   // define database related variables
   $database = 'database_name_here';
   $host = 'localhost';
   $user = 'root';
   $pass = '';

   // try to conncet to database
   $dbh = new PDO("mysql:dbname={$database};host={$host};port={3306}", $user, $pass);

   if(!$dbh){

      echo "unable to connect to database";
   }
   
?>

HTML and PHP Code Page to display paginated data (index.php)

Below is the part of HTML/PHP code which renders data from database with pagination using php. This page requires php code to get data from database ( data.php ), and data.php requires database-config.php to connect to database. 


<!-- Display messages from database-->
      <div class="col-md-10 col-md-offset-2 content">
                <table class="table table-striped">
                  <thead>
                   <th>Message</th>
                  </thead>
                  <tbody>
                   <?php 
                      for ($i=0; $i<count($result); $i++) { 
                          echo"<tr><td>".$result[$i]."</td><tr/>";
                      }
                   ?>
                  </tbody>
                </table>
      </div>  
        <!-- Render pagination based on messages-->
      <div class="pagination-wrap">
                <ul class="pagination">
                  <?PHP

                    if($page_counter == 0){
                        echo "<li><a href=?start='0' class='active'>0</a></li>";
                       for ($j=1; $j < $paginations; $j++) { 
                          echo "<li><a href=?start=$j>".$j."</a></li>";
                       }
                    }else{
                        echo "<li><a href=?start=$previous>Previous</a></li>"; 
                        for ($j=0; $j < $paginations; $j++) {
                         if ($j == $page_counter) {
                            echo "<li><a href=?start=$j class='active'>".$j."</a></li>";
                         }else{
                            echo "<li><a href=?start=$j>".$j."</a></li>";
                         } 
                      }if($j != $page_counter+1)
                        echo "<li><a href=?start=$next>Next</a></li>"; 
                    } 
                    
                  ?>
                </ul>
      </div>

PHP code to retrieve data using pagination links (data.php)



<?php 
 require 'database-config.php';

    // Variables for the first page hit
 $start = 0;
 $page_counter = 0;
    $per_page = 5;
    $next = $page_counter + 1;
    $previous = $page_counter - 1;

    // Check the page location with start value sent by get request and change variable values accordingly
 if(isset($_GET['start'])){
  $start = $_GET['start'];
  $page_counter =  $_GET['start'];
  $start = $start *  $per_page;
  $next = $page_counter + 1;
  $previous = $page_counter - 1;
 }

 
 
    // query to get messages from messages table
 $q = "SELECT id,message FROM messages LIMIT $start, $per_page";

 $query = $dbh->prepare($q);

 $query->execute();
    
    //placeholder variable to store result
 $result = null;

 if($query->rowCount() == 0){
 }else{

  while($row = $query->fetch(PDO::FETCH_ASSOC)){
       // store each row in result variable 
    $result[] = $row['id']." ".$row['message'];
  }
  
 }

    // query to get total number of rows in messages table
 $count_query = "SELECT * FROM messages";

 $query = $dbh->prepare($count_query);

 $query->execute();

 $count = $num_rows = $query->rowCount();
    
    // calculate number of paginations required based on row count 
 $paginations = ceil($count / $per_page);


?>

A bit of styling for pagination links using css (style.css)



.info,.pagination-wrap{text-align: center;}
h2{padding: 10px;}
.pagination li a.active{background: #428BCA;
color: white;}

If you run into any issues you can download the source file from provide link and go through the code. Do not forget to comment if you like this tutorial or have any issues. Happy to help cheers :)

Contact Form

Name

Email *

Message *

Labels

Follow TechYari on

Translate

About TechYari

Tech Yari is a Technical Blog featuring articles on Web Development, Web Design, Search Engine Optimization, Social Media Marketting and Programming.