Follow

Welcome to TechYari!

Tutorials on webdesign, web development and more...
CRUD (Create, Read, Update and Delete) are one of the most important operations for a web application. In this tutorial, I will show you how to use PHP with PDO and MySql database for CRUD operations. I will be creating a simple quotes app where a user can publish a quote he likes. The homepage will contain a list of quotes with links to Update and Delete each quote.

crud in php with pdo and mysql

Download Source Live Demo



To keep this tutorial simple and focused to CRUD operations I have left validations for user part, it means anyone can update and delete the quotes. If you would like to make it secure you can go through one of the earlier tutorial Role base login in PHP with MySql  and implement session control to make it secure.

Lets start with creating our table first.

Database Table Setup

Create a table called demo_quotes with two columns (id and text). Take a look at below script if you have any doubts, you can directly run this in sql window of phpmydmin.


CREATE TABLE demo_quotes(
   id INT NOT NULL AUTO_INCREMENT,
   text VARCHAR(1000) NOT NULL,
   PRIMARY KEY (id)
);


Connect to database from PHP using PDO

Use below script to connect to database using PDO. Create a file named database-config.php and paste below code, we will import this file wherever we need to perform database related operations.


<?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";
   }
   
?>



Creating the Home Page

We will create a file called index.php. This file will serve following purpose :

1. Display a form to post new quotes.
2. Show a list of posts from database by performing READ operation and display edit and delete links with each quote.
3. Display an editable form when user clicks on edit link for any of the quotes in the list.
4. Show appropriate errors if any based on url parameter.

First of all we will include database-config.php at top of this file as we need to perform database related operations.

Next we need to define an associative array for our errors so that we can display errors based on url parameters being received from crud.php script. 

Next we check for action and id parameters in url, if present we display the edit form and if not then we display the homepage.

Below is the code for index.php (homepage).


  <?php 
  // Import database connection script
  require 'database-config.php';
  ?>

  <!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>CRUD example in PHP with MySql database</title>
  <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="title"> <h2>CRUD example in PHP with MySql database</h2></div>
      <?php 

                                 // Set default error messages 
      $errors = array(
        1=>"Please provide values for all the fields"
        );

                                 // check if url contains an error code as a parameter
      $error_id = isset($_GET['err']) ? (int)$_GET['err'] : 0;

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


  /* check if url contains any action parameters and load the parts accordingly

    Load index page with a form filed and all quotes if action parameter is not

    present. Load edit quote form if action parameter is present*/


    $action= "";
    $id="";

    if(isset($_GET['action']) && isset($_GET['id'])){

        $action = $_GET['action'];

         $id = $_GET['id'];
                                  }

    if($action=="edit" && $id!=""){ 

    /* if an edit action is present, get the quote with help of id parameter
                                       
    display the quote in an editable form and bind crud.php (update action) 

    using hidden input tag. */


    $q = 'SELECT * FROM demo_quotes WHERE id = :id';

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

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

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

    ?>

    <div class="article-form">
      <form action="crud.php" method="POST">  
        <textarea name="text" maxlength="300"><?php echo $row['text'];?></textarea>
        <input type="hidden" name="id" value="<?php echo $id; ?>" />
        <input type="hidden" name="action" value="update" /><br/>
        <input type="submit" value="Update"/>
      </form>
    </div>

    <?php }else{ ?>

    <!-- This section displays an HTML form to publish posts. It also lists all the posts
                                       
      from the database in a table with EDIT and DELETE links to each of them. 

      This part of code will only run if there is no action parameter present in the URL. 
    -->

    <div class="article-form">
      <form action="crud.php" method="POST">  
        <textarea name="text" maxlength="300" placeholder="Input text here" required autofocus></textarea><br/>
        <input type="submit" value="publish"/>
      </form>
    </div>
     <br/>
     <br/>
    <div class="articles">
      <table>
        <thead>
          <th colspan="3">All Quotes</th>
        </thead>
          <tbody>

            <?php 

              $q1 = 'SELECT * FROM demo_quotes';

              $query1 = $dbh->prepare($q1);

              $query1->execute();

              if($query1->rowCount() == 0){
                  echo "<tr><td colspan='3'>No data available</td></tr>";
                }else{
                  while($row1 = $query1->fetch(PDO::FETCH_ASSOC)){

                      /* Here we print each quote in a row with EDIT and DELETE links. We pass the quote ID as a parameter
                                                          
                         to crud.php script and perfom edit and delete operation on an item */ 
                        
                        echo'<tr><td>' . $row1['text'] . '</td><td><a href="index.php?action=edit&id='.$row1['id']. '" class="edit">Edit</a></td><td><a href="crud.php?action=delete&id=' .$row1['id']. '" class="delete">Delete</a></td></tr>';
                    }
                  }
            ?>

          </tbody>
      </table>
    </div>

    <?php } ?>



  </body>
</html>


Styling the Home Page with CSS

We need to make our homepage look a bit cleaner. Copy and paste below style rules in a style.css file and link it properly to your index.php file.


/* Styling for home page */
.title{text-align: center;}
textarea{width: 400px;padding: 20px;}
.article-form{text-align: center; padding: 20px;width: 400px;margin: auto;}
.article-form input{
 float:right;padding: 5px;border: none;
 background: lightblue;
 color: #ffffff;
 font-weight: bold;
 font-size: inherit;
 margin-right: -40px;
}
.articles{max-width:100%;}
table{margin:auto;width: 600px;}
thead{background: lightblue}
th,td{padding:5px;border-bottom: 1px solid rgb(143, 207, 240);}
.edit{
 text-decoration: none;
 background: rgb(211, 184, 34);
 color: white;
 padding: 3px 7px;
 font-weight: 500;
}
.delete{
 text-decoration: none;
 background: rgb(211, 74, 34);
 color: white;
 padding: 3px 7px;
 font-weight: 500;

}


Performing  Create, Update and Delete Operations 

In order to insert, update and delete data we will create a crud.php file, this file will perform following operations

1. Check GET/POST request and retrieve action value ( Update/Delete ).
2. UPDATE a quote.
3. DELETE a quote.
4. INSERT a new quote.

At the beginning of this file we have a variable named action. this variable will hold the data passed by GET or POST request as action parameter. We will compare action variable value to decide which operation needs to be performed. The default would be an insert operation.

below is the code for CRUD operations


<?php 
 require 'database-config.php'; // import database connection script
    
    // Initialize action variable with empty string
    $action = "";
    
    // Check if we have action parameter with GET or POST request and set action value accordingly
 if(isset($_GET['action'])){
  $action = $_GET['action'];
 }

 if(isset($_POST['action'])){
  $action = $_POST['action'];
 }

 // Perform an UPDATE operation when action variable contains update

    if($action == "update"){
     $id = "";
        $text = "";
     if(isset($_POST['id'])){
   $id = $_POST['id'];
  }

  if(isset($_POST['text'])){
   $text = $_POST['text'];
  }

  if($text!="" && $id!=""){

   $q = 'UPDATE demo_quotes SET text=:text WHERE id=:id';

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

   $query->execute(array(':text' => $text, ':id' => $id));

   header('Location: index.php'); // Return to index page

  }else{

   header('Location: index.php?err=1'); // Return to index page with an error
  }

  

    }elseif($action == "delete"){    // Perform DELETE operation when action variable contains update
     $id = "";
     if(isset($_GET['id'])){
   $id = $_GET['id'];
  }

  if($id!=""){

   $q = 'DELETE from demo_quotes WHERE id=:id';

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

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

   header('Location: index.php'); // Return to index page
  }else{

   header('Location: index.php?err=1'); // Return to index page with an error
  }
    }else{               // Perform an INSERT operation when action is not equal to update/delte

        $text = "";

  if(isset($_POST['text'])){
   $text = $_POST['text'];
  }

  if($text!=""){

   $q = 'INSERT INTO demo_quotes(text) VALUES (:text)';

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

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

   header('Location: index.php'); // Return to index page
  }else{

   header('Location: index.php?err=1'); // Return to index page with an error
  }

    }


?>

This is it. We have created a simple website capable to perform CRUD ( Create, Read, Update, Delete) operations using PDO with MySql database. Leave a comment if you have any queries or suggestions.  
Security is very essential to any web application. SQL injection is a technique where attacker tries to execute malicious scripts on application's database using several security flaws. The easiest way to do this is sending the SQL script via get or post request that do not have proper validation and security filtering on server.In this post we will look at how to prevent sql injection using two main techniques.

how to prevent sql injection in php


Lets assume we have a login page having two form fields, one for username and another for password. We will be using POST method to submit this data to the server. When user clicks on Sign in button all the data will be submitted to server and authenticate.php script will take care of validation.

Below is the HTML code for the typical login form:


<form action="authenticate.php" method="POST">  
    <input type="text" name="username" placeholder="Username" required autofocus/><br/>
    <input type="password" name="password" placeholder="Password" required/><br/>
    <input type="submit" value="Sign in"/>
</form>


There are several ways you can prevent SQL injection while submitting the data from login form to server:

1. Using PDO
2. Using MySqli
3. Escaping special characters

Let's talk about each one of them :

Prepared Statements with PDO and MySqli

You can use PDO to achieve this. Using PDO is considered the best option however it requires the PDO extension to be enabled on you server. Most of the servers running PHP 5.3 or later have this option enabled and if not you can check with you hosting provider and ask them to enable the extension.

Using PDO : Below is an example of using PDO to prevent SQL injection.



 <?
 // define database related variables
   $database = 'your_database_here';
   $host = 'localhost';
   $user = 'your_db_username';
   $pass = 'your_db_password';

   // 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";
   }

    // Create placeholder variables
 $username = "";
 $password = "";
 
 // Check if the values are set and assign to variables
 if(isset($_POST['username'])){
  $username = $_POST['username'];
 }
 if (isset($_POST['password'])) {
  $password = $_POST['password'];

 }
 
 // Check if user has entered some values
 if($username!="" && $password!=""){

      // Create query
   $q = 'SELECT * FROM users WHERE username=:username AND password=:password';
      // Prepare query using PDO
   $query = $dbh->prepare($q);
      // Execute query
   $query->execute(array(':username' => $username, ':password' => $password));


   if($query->rowCount() == 0){
    
    // Send back to login page with an error message

   }else{
    
    // Add user to session and take him to home page.
   }
 }else{

   // Back to login page with error message. 

 }

   

  ?> 

Using MySqli : Below is an example of using MySqli to prevent SQL injection.




 <?
 // define database related variables
   $database = 'your_database_here';
   $host = 'localhost';
   $user = 'your_db_username';
   $pass = 'your_db_password';

  $mysqli = new mysqli($host, $user, $pass, $database);
  
  if ($mysqli->connect_errno) {
    echo "Failed to connect to database: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }

    // Create placeholder variables
 $username = "";
 $password = "";
 
 // Check if the values are set and assign to variables
 if(isset($_POST['username'])){
  $username = $_POST['username'];
 }
 if (isset($_POST['password'])) {
  $password = $_POST['password'];

 }
 
 // Check if user has entered some values
 if($username!="" && $password!=""){
            
            // Prepare statement
   $stmt = $mysqli->prepare('SELECT * FROM users WHERE username=? AND password=?');
   if (!$stmt->bind_param("i", $username,$password)) {
        echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
   }

   // Execute statement
   if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
   }
       
       // Get result 
            $result = $stmt->get_result(); // This method requies mysqlnd drives. pleas eamke sure it is available or else you will get errors.
            
            // Check number of rows returned from database.
            if($result->num_rows > 0){

             //fetch the data and login user

            }else{

             // Back to login page with error as username and password does not match.
            }

  }else{

         // Back to login page with error message. 
  }

 
  ?> 

We have seen both ways of submitting data which can save you from sql injection. We also talked about escaping special charatacters which can be used to prevent sql injection as well. Below is an example of how you can escape special characters while getting data from our login page.

Using  mysql_real_escape_string to escape special characters



  // Create placeholder variables
 $username = "";
 $password = "";
 
 // Check if the values are set and assign to variables
 if(isset($_POST['username'])){
  // check to see if there are any special characters, remove them and assign safe value to username variable
  $username = mysql_real_escape_string($_POST['username']);
 }
 if (isset($_POST['password'])) {
  // check to see if there are any special characters, remove them and assign safe value to password variable
  $password = mysql_real_escape_string($_POST['password']);

 }

That's all for today. If you have any queries or suggestions feel free to comment below. Cheers :)
In this tutorial I am going to show you how to build a rating system in php using jQuery, Ajax and MySql. We will be using jQuery to show rating stars and we will also make ajax request when user clicks on a star to rate an article. MySql databse is being used to store our article and related rating data for each article.

To start we need to create two tables, one for storing articles and another for storing ratings for those articles by different users. In order to keep it simple I am leaving the user part. So we will have anonymous ratings ( Just to keep it simple ).


Download Source Live Demo


Setting Up Tables for article and ratings


Below is the script to create article and article rating table. Run this script in your database and populate article table with few entries manually to test.


CREATE TABLE article(
   id INT NOT NULL AUTO_INCREMENT,
   text VARCHAR(200) NOT NULL,
   PRIMARY KEY (id)
);

CREATE TABLE article_rating(
   article_id INT NOT NULL,
   rating INT NOT NULL
);

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


Create a PHP file and use below code to connect to MySql from PHP. Change variable values according to your environment.


<?php
   // define database related variables
   $database = 'your_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";
   }
   
?>

Inserting user ratings to database via PHP (rate.php).


To rate each article we will store article id and article rating to previously created article_rating table. Here we receive article id and rating from an ajax GET request.


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

 $id = "";
 $rating = "";
 
 if(isset($_GET['id'])){
  $id = $_GET['id'];
 }
 if (isset($_GET['rating'])) {
  $rating = $_GET['rating'];

 }
 
 

 $q = 'INSERT INTO article_rating(article_id,rating) VALUES (:id,:rating)';

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

 $query->execute(array(':id' => $id, ':rating' => $rating));


 if($query->rowCount() != 0){
  echo "rated successfully";
 }else{
  echo "There was an error";
 }


?>

PHP code to get articles and their ratings from database.


Create an index.php file and paste following code at top section before html tag. The code listed below gets all the articles and their ratings from the database and saves it into an array. We will be using this array to show them later (index.php).


<?PHP 
    
      require 'database-config.php';
      // Get all the articles from the database
      $q = 'SELECT * FROM article';
      $query = $dbh->prepare($q);
      $query->execute();


    // Iterate for each article returned via query  
    $articles = array(); 
    
    while($row = $query->fetch(PDO::FETCH_ASSOC)){
         $data = "";
         $id = $row['id'];
         $text = $row['text'];
         $average = 0;
         
         // Get total count of rating for an article
         $q1 = 'SELECT count(*) FROM article_rating where article_id=:id';
         $query1 = $dbh->prepare($q1);
         $query1->execute(array(':id' => $id));
         $row1 = $query1->fetch(PDO::FETCH_ASSOC);
         $count = $row1['count(*)'];
         
         if($count > 0){
             // Get all ratings for an article
             $q2 = 'SELECT rating FROM article_rating where article_id=:id';
             $query2 = $dbh->prepare($q2);
             $query2->execute(array(':id' => $id));
             
             // Sum up the ratings 
             $rating = 0; 
             while($row2 = $query2->fetch(PDO::FETCH_ASSOC)){
               $rating = $rating + $row2['rating'];
             } 
             
             //Calculate average rating by deviding the sum by total ratings and rounding the result. 
             $average = ceil($rating/$count);
         }else{

             $average = 0;
         }
         
         $data = array($id,$text,$average);
         //Store each article and related rating in articles array
         $articles[] = $data;
    }
   
?>

Code to show articles on homepage (index.php).


Now use following code between body tags to show articles in your index.php file. I am using twitter bootstrap for alignment purpose. Please include that as well in your index.php file to get desired results or you can also style them yourself.


       <?php for($i = 0; $i<sizeof($articles);$i++){ ?>

                      <div class="article row" article-id="<?php echo $articles[$i][0] ?>">
                        <div class="id col-md-2"><?php echo $articles[$i][0] ?></div>
                        <div class="text col-md-7"><?php echo $articles[$i][1] ?></div>
                        <div class="rating col-md-3 <?php echo $articles[$i][2] ?>"><?php echo $articles[$i][2] ?></div>
                      </div>

                     <?php } ?> 

Styling star ratings (style.css).


Create a css file and paste below code, save with any name and include the file in your index.php file created earlier


.info{text-align: center;}
.row{padding: 10px;
background: beige;
margin-bottom: 5px;
font-size: 16px;
font-weight: 600;}
h2{padding: 10px;}
.gray{color:rgb(189, 187, 187)}
.red{color:red;}

Creating star icons for rating, applying hovers styles for stars and making ajax request when user selects a rating. (main.js)


Create a javascript file and paste below code, you also need to include this file in your index.php file.
Here we achieve three things
1. We apply star icons using bootstrap classes based on rating numbers.
2. When user hovers over a star to rate an article we highlight the stars by checking the star position and show him a nice effect using jquery
3. Lastly when user selects a rating by clicking on a star we make an ajax request with jquery and insert the data into our article_rating table.


$(document).ready(function(){

 // Apply style based on ratings from database

 $('.5').html('<span class="glyphicon glyphicon-heart" rating="1"></span><span class="glyphicon glyphicon-heart" rating="2"></span><span class="glyphicon glyphicon-heart" rating="3"></span><span class="glyphicon glyphicon-heart" rating="4"></span><span class="glyphicon glyphicon-heart" rating="5"></span>');
  $('.4').html('<span class="glyphicon glyphicon-heart" rating="1"></span><span class="glyphicon glyphicon-heart" rating="2"></span><span class="glyphicon glyphicon-heart" rating="3"></span><span class="glyphicon glyphicon-heart" rating="4"></span><span class="glyphicon glyphicon-heart gray" rating="5"></span>');
   $('.3').html('<span class="glyphicon glyphicon-heart" rating="1"></span><span class="glyphicon glyphicon-heart" rating="2"></span><span class="glyphicon glyphicon-heart" rating="3"></span><span class="glyphicon glyphicon-heart gray" rating="4"></span><span class="glyphicon glyphicon-heart gray" rating="5"></span>');
    $('.2').html('<span class="glyphicon glyphicon-heart" rating="1"></span><span class="glyphicon glyphicon-heart" rating="2"></span><span class="glyphicon glyphicon-heart gray" rating="3"></span><span class="glyphicon glyphicon-heart gray" rating="4"></span><span class="glyphicon glyphicon-heart gray" rating="5"></span>');
     $('.1').html('<span class="glyphicon glyphicon-heart" rating="1"></span><span class="glyphicon glyphicon-heart gray" rating="2"></span><span class="glyphicon glyphicon-heart gray" rating="3"></span><span class="glyphicon glyphicon-heart gray" rating="4"></span><span class="glyphicon glyphicon-heart gray" rating="5"></span>');
      $('.0').html('<span class="glyphicon glyphicon-heart gray" rating="1"></span><span class="glyphicon glyphicon-heart gray" rating="2"></span><span class="glyphicon glyphicon-heart gray" rating="3"></span><span class="glyphicon glyphicon-heart gray" rating="4"></span><span class="glyphicon glyphicon-heart gray" rating="5"></span>');



 // Appy style on hover by user

 $("span[rating='1']").hover(function(){
  console.log("selected 1");
  $(this).addClass('red');
  },function() {
        $( this ).removeClass('red');
     }
 );

 $("span[rating='2']").hover(function(){
  console.log("selected 1");
  $(this).prev().addClass('red');
  $(this).addClass('red');
  },function() {
   $( this ).prev().removeClass('red');
        $( this ).removeClass('red');
     }
 );

 $("span[rating='3']").hover(function(){
  console.log("selected 1");
  $(this).prev().prev().addClass('red');
  $(this).prev().addClass('red');
  $(this).addClass('red');
  },function() {
   $( this ).prev().prev().removeClass('red');
   $( this ).prev().removeClass('red');
        $( this ).removeClass('red');
        
     }
 );

 $("span[rating='4']").hover(function(){
  console.log("selected 1");
  $(this).prev().prev().prev().addClass('red');
  $(this).prev().prev().addClass('red');
  $(this).prev().addClass('red');
  $(this).addClass('red');
  },function() {
   $( this ).prev().prev().prev().removeClass('red');
   $( this ).prev().prev().removeClass('red');
   $( this ).prev().removeClass('red');
        $( this ).removeClass('red');
        
     }
 );

 $("span[rating='5']").hover(function(){
  console.log("selected 1");
  $(this).prev().prev().prev().prev().addClass('red');
  $(this).prev().prev().prev().addClass('red');
  $(this).prev().prev().addClass('red');
  $(this).prev().addClass('red');
  $(this).addClass('red');
  },function() {
   $( this ).prev().prev().prev().prev().removeClass('red');
   $( this ).prev().prev().prev().removeClass('red');
   $( this ).prev().prev().removeClass('red');
   $( this ).prev().removeClass('red');
        $( this ).removeClass('red');
        
     }
 );
 
    // Making ajax request when user selects a rating for an article.
 $('.glyphicon').click(function(){

  var rating = $(this).attr('rating');
        var id = $(this).parent().parent().attr('article-id');
  console.log(rating);
  console.log(id);

  $.ajax({
       url: "rate.php",
       type: 'GET',
       data: {id : id,rating:rating},
       success: function(data) {  
       console.log(data); 
       location.reload();
   },
      error: function(e) {
      console.log(e); 
  }
 });
 })

});

That's it we have build a rating system in php using jQuey and Ajax. If you run into any issues you can download the source code from here
I hope you enjoyed this article. Please share your thoughts and queries using comment box below the article.
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 :)
Today we are going to look at another API called Freebase.com . Freebase has community driven database of people, places, things and much more. We will create a simple search app with jQuery and Ajax. Our app will auto suggest things using freebase.com API, jQuery and Ajax when a user types more than 3 characters in search box. Each auto suggested link will contain it's category (As there can be many different items with same name ) and a hidden page url of freebase.com for that topic. If a user clicks on an our app will show a box dynamically below the search box using jQuery. In addition it will also hide the box if you delete the searched item or press back key on your keyboard.
   
Requirements :  This tutorial requires following libraries to work :
  • jQuery 
  • jQuery UI ( for Ajax and autosuggest )

Scenario 1 : Our Home Page



Scenario 2: Dropdown with auto suggest using jQuery when user searches for something




Scenario 3 : Result with a link to freebase.com for the selected item.



Download Source  Demo


Kindly include jQuery and jQuery UI properly before starting with the code of the tutorial. Download the source code if you have nay doubts.


<div class="search-container">
                <h3>What are you looking for :</h3>
                <div class="search">
                <input class="search-box" id="search-box" name="search-input" onkeyup='check()' placeholder="Enter anything here"/>
                </div>
</div>
<div class="result">

</div>


<style type="text/css">
       body{background: rgba(167, 166, 166, 0.22);}
      .search-container{
            
            width: 520px;
            text-align: center;
            padding: 20px;
            margin: auto;
            color: gray;
            background: white;
            -webkit-box-shadow: 5px 5px 25px 0px rgba(46, 50, 50, 0.56);
-moz-box-shadow:    5px 5px 25px 0px rgba(46, 50, 50, 0.56);
box-shadow:         5px 5px 25px 0px rgba(46, 50, 50, 0.56);

      }

      .result{
        margin: auto;
        width: 500px;
        padding: 20px;
        margin-top: 20px;
        text-align: center;
        background: rgb(246, 247, 242);
        padding: 31px;
        display: none;
          -webkit-box-shadow: 5px 5px 25px 0px rgba(46, 50, 50, 0.56);
-moz-box-shadow:    5px 5px 25px 0px rgba(46, 50, 50, 0.56);
box-shadow:         5px 5px 25px 0px rgba(46, 50, 50, 0.56);
      }

      .result a{text-decoration: none;font-size: 20px;color: gray}

      .search-box{width: 500px;padding: 5px 10px;
                  border: 1px solid rgb(152, 187, 211);
                  height: 25px;
                  -webkit-box-shadow: inset 2px 1px 25px 0px rgba(109, 132, 180, 0.22);
-moz-box-shadow:    inset 2px 1px 25px 0px rgba(109, 132, 180, 0.22);
box-shadow:         inset 2px 1px 25px 0px rgba(109, 132, 180, 0.22);
                }
      footer{text-align: center;margin-top: 300px}          
     </style>


<script type="text/javascript">
        function check(){
        var value=$.trim($("#search-box").val());

        if(value.length>0)
      {
        $('.result').hide();
      }
      }
     </script>
<script type="text/javascript">
$(document).ready(function(){

 // populating the dropdown list using autocomplete with freebase api 
$( "#search-box" ).autocomplete({
      source: function( request, response ) {
        $.ajax({
          url: "https://www.googleapis.com/freebase/v1/search",
          dataType: "json",
          data: {
            query: request.term,
            mode:"json"
          },
          success: function(data) {
            // Fix for IE 8 as forEach function not supported yet below IE 9
        if (typeof Array.prototype.forEach != 'function') {
         Array.prototype.forEach = function(callback){
           for (var i = 0; i < this.length; i++){
             callback.apply(this, [this[i], i, this]);
           }
         };
          }
            var parsed = data.result;
            console.log(parsed);
             var newArray = new Array(parsed.length);
             var i = 0;
              parsed.forEach(function (entry) {
                     var category="Not Available";
                     if(entry.notable){category = entry.notable.name;}
                     var newObject = {
                         label: entry.name+ " (" + category + ")",
                         mid:entry.mid,
                         id:entry.id
                     };
                     newArray[i] = newObject;
                     i++;
                 });

              response(newArray);
              //console.log(newArray);
  
          }
        });
      },
      minLength: 3,
      select: function( event, ui ) {
        /*Get the item's mid and create a freebase link for the item  */
        $('.result').show();
        $('.result').html('<a href=http://freebase.com'+ui.item.mid+' target="_blank">Click here to know more about <span style="color:rgb(53, 179, 219)">'+ui.item.label+'</span></a>');

      },
      open: function() {
        $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
      },
      close: function() {
        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
      }
    });

});
</script>



You can download the source code of this tutorial if you get into any trouble using this link.

Kindly share this if you like it. Comment below for queries and suggestions. Happy Coding :)

Introduction

Everyone wants to have his own website, in this post I am going to show you one of the easiest way to create one using html5, css3 and jQuery. I will also add one slider to the homepage. This will be a single page website but you can copy the code and manipulate it to create a website with multiple pages in the same way.

What we need  :




Download Source  Demo

Step 1 : Creating the html page

We need to create the basic markup with css classes which will be used later to add style to the page. In order to make things easier we need a css framework. There are many frameworks available and I will be using Twitter Bootstrap for this website creation tutorial. We also need a jQuery plugin to create the desired slider on homepage. We will use jQuery Nivo Slider plugin to achieve this. Below is the html markup :


<!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>TechYari - HTML5, CSS3, JavaScript Demo & Tutorials</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="plugins/nivo-slider/themes/default/default.css" type="text/css" media="screen" />
     <link href="plugins/nivo-slider/nivo-slider.css" rel="stylesheet">
    <link href="css/main.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/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
   <header class="navbar">
    <div class="container">
     <div class="col-md-8 navbar-header">
        <a href="#">TechYari</a>
     </div>
        <div class="col-md-4 main-navigation">
          <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>
          </ul>
      </div>
    </div> 
    
   </header>
   <div class="wrapper">
     <div class="slider-bg">
      <div class="container">
     <div class="col-md-8 col-md-offset-2">
             <div class="slider-wrapper theme-default">
              <div id="slider" class="nivoSlider">
                <img src="img/1.jpg" data-thumb="img/1.jpg" alt="" />
                <a href="http://techyari.in"><img src="img/1.jpg" data-thumb="img/2.jpg" alt="" title="This is an example of a caption" /></a>
                <img src="img/2.jpg" data-thumb="img/3.jpg" alt="" data-transition="slideInLeft" />
                <img src="img/3.jpg" data-thumb="img/4.jpg" alt="" title="#htmlcaption" />
              </div>
            <div id="htmlcaption" class="nivo-html-caption">
                <strong>This</strong> is an example of a <em>HTML</em> caption with <a href="#">a link</a>. 
            </div>
        </div>
     </div>
     </div>
   </div>
   <div class="container">
     <div class="row">
     <div class="col-md-4">
        <div class="intro">
            <div class="image"> <img src="img/iPad.png"/></div>
            <h2>Introducing new iPad</h2>
            <p>Lorem ipsum dollor Lorem ipsum dollor Lorem ipsum dollorLorem ipsum dollorLorem</p>
        </div>
      
     </div>
     <div class="col-md-4">
         <div class="intro">
            <div class="image"><img src="img/monitor.png"/></div>
            <h2>Fall in love with MacBook</h2>
            <p>Lorem ipsum dollor Lorem ipsum dollor Lorem ipsum dollorLorem ipsum dollorLorem</p>
        </div>
     </div>
     <div class="col-md-4">
         <div class="intro">
            <div class="image"><img src="img/Printer.png"/></div>
             <h2>Wirelss Printing</h2>
            <p>Lorem ipsum dollor Lorem ipsum dollor Lorem ipsum dollorLorem ipsum dollorLorem</p>
        </div>
     </div>
     </div>
     <hr class="half-rule">
     <div class="tagline">
        <p>This is an awesome website. You will love it for sure</p>
        <a href="#">Download Source Code</a>
     </div>
      </div>
   </div>
    <div class="credits">
      <div class="container">
         <div class="col-md-4">
            <h4>Credits & Attributions:</h4>
         </div>
          <div class="col-md-4">
            <p>Images :</p>
            <ul>
              <li><a href="https://www.flickr.com/photos/katsrcool/14511055622/">Kool Cats Photography</a></li>
               <li><a href="https://www.flickr.com/photos/breatheoutnow/14505171801/">breatheoutnow</a></li>
                <li><a href="https://www.flickr.com/photos/118118485@N05/14535481923/">Michael D Beckwith</a></li>
            </ul>
         </div>
          <div class="col-md-4">
            <p>Scripts :</p>
            <ul>
              <li><a href="http://jquery.com/">jQuery</a></li>
              <li><a href="http://getbootstrap.com/">Bootstrap</a></li>
              <li><a href="http://dev7studios.com/plugins/nivo-slider/">Nivo Slider</a></li>

            </ul>
         </div>
      </div>
    </div>
   

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
 <footer>
        &copy 2014 Techyari.in | All rights reserved
    </footer>

  </body>
</html>

So we have our markup ready, now we need to style it. Use below css code to style the page :


/********** General Styles *********/
body{font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;}
p{color:#555;}
.navbar{ height:50px;background:#ffffff;color:gray;margin-bottom: 0px;}
.navbar-header{padding-top: 5px;}
.navbar-header a{font-weight: bold;font-size: 32px;line-height: 32px;color:gray;text-decoration: none;}
.wrapper{min-height:500px; margin-bottom: 20px;}
.post-title h2{text-align: center; margin-bottom: 50px;}
.post-title a{text-decoration: none;}
footer{border-top: 1px solid gray;text-align: center;}


/********** Navigation *********/

.main-navigation ul li{float: left;list-style-type: none;margin: 10px 0px 0px 10px}
.main-navigation ul li a{text-decoration: none;color:#555;font-size: 14px;;}
.main-navigation ul li a:hover,.main-navigation ul li a:focus,.main-navigation ul li a:active{color:#428bca;}
.slider-bg{background: #244363;padding: 20px 0px 20px 0px;margin-bottom: 20px;}
.intro{text-align: center;}
.half-rule {width: 100px;margin: 40px auto;}
.tagline{text-align: center;}
.tagline p{font-size: 20px;font-weight: bold;}
.tagline a{text-decoration: none;padding: 6px 10px;border: 1px solid gray;border-radius: 5px;}
.credits{text-align: left; margin-top: 100px;background: rgb(57, 93, 156);padding: 10px;color: white;}
.credits p{color: white}
.credits ul li{list-style-type: none}
.credits a{color: white}

Our website is almost ready now...we just need to call jQuery NivoSlider plugin to activate the slider. Add below code to the footer area of website and refresh your browser. Download source code and try it if you get into any trouble.



<script type="text/javascript">
    $(window).load(function() {
        $('#slider').nivoSlider();
    });
    </script>


That's it we have created a simple yet beautiful website with very few lines of code. Kindly share this tutorial if you found it useful. Use comment box below for any suggestions and doubts. Happy coding. Cheers :)

Introduction

Today I am going to create three simple yet beautiful animated hover popup using jQuery, HTML and CSS.
I will be using below functions/events provided by jQuery to achieve this effect

1. mouseenter() - to show the popup when user enters mouse over the link/button.
2. mouseleave() - to hide the popup when user leaves the button.
3. fadeToggle() - to add animation to the popup window, you can use other functions to create different effects according to your needs.

Demo

In order to create this I have used twitter bootstrap with jQuery. There are many different ways to style a hover popup, one is using images but I have styled this popup using css3 and it may not work in older browsers ( IE 9 and earlier ). I have tested this using chrome, you can tweak it to work on other browsers as well.

HTML Code



<div class="container">
      <div class="post-title">
     <h2><a href="#">Creating an animated hover popup using jQuery and CSS3</a></h2>
      </div>

      <div class="row hover-demo">
        <div class="col-md-4">
          <div class="outer-wrapper">
            <div class="on-hover-content">
            <img src="img/mustang.jpg">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris malesuada turpis metus, vitae fermentum mauris imperdiet ut. Suspendisse aliquam</p>
            </div>
            <a type="button" class="btn btn-primary">An Image with text</a>
           </div>
        </div>
        <div class="col-md-4">
           <div class="outer-wrapper">
            <div class="on-hover-content">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris malesuada turpis metus, vitae fermentum mauris imperdiet ut. Suspendisse aliquam</p>
            </div>
            <a type="button" class="btn btn-success">A paragraph</a>
        </div>
        </div>
        <div class="col-md-4">
           <div class="outer-wrapper">
            <div class="on-hover-content">
              <img src="img/mustang.jpg">
            </div>
          <a type="button" class="btn btn-info">Image only</a>
        </div>
        </div>
      </div>
   </div>

CSS Code


.hover-demo{margin-top: 220px;}
.hover-demo{text-align: center;}
.on-hover-content{position: absolute;bottom: 40px;background-color: whitesmoke;padding: 10px;border-radius: 10px;}
.on-hover-content img{width:360px;}
#dynamic-content{width: 360px;overflow: scroll;}

In this HTML code I have created 3 links and  styled them as buttons using bootstarps classes. All of them have on div element as a sibling which contains the hover popup content to be shown while someone hovers over the links. We will hide these popup content initially using jQuery's hide() method and the we will use mouseenter() and mouseleave() to show and hide hover popup content.

Below is the jQuery code to achieve the result.



 <script type="text/javascript">
      $(document).ready(function(){
          $("div.on-hover-content").hide();
      });

      $(".btn").mouseenter(function(){
        $(this).siblings("div.on-hover-content").fadeToggle( "slow", "linear" );
      })
      .mouseleave(function(){
         
        $(this).siblings("div.on-hover-content").fadeToggle( "slow", "linear" );
      });

    </script>
That's all we have created a nice hover popup in no time with few lines of code using jQuery.

Kindly share this tutorial if you like it :). Leave comments below for suggestions and doubts. 

What is a Wordpress Plugin

Plugins are small piece of software program that can integrate with your wordpress installation and add additional features like gallery support for images, carts for e-commerce sites, spam detection for comments and much more.

Everyone uses plugins to optimize and make their blog more interactive and Wordpress plugin directory has huge number of plugins to accommodate everyone's needs. Below is a list of few popular plugins that can help you get most of your blogs.

W3 Total Cache

W3 Total Cache is a plugin that can improve your websites performance by various methods like caching, minifying and using content delivery networks.



Jetpack

Jetpack adds a lot of features like simple stats, email subscription, likes, comment system with social networking, contact forms and much more.



iThemes Security

Security is one of the most important aspect for any blogger or organization. iThemes Security is one of the most popular plugin to make your blog secure from hackers.



NextGen Gallery

NetGen Gallery is one of the most downloaded gallery plugins with over 10 million downloads. It provides abilities like batch uploads,import metadata, edit thumbnails, group galleries into albums and much more.



Kindly share and reply with comments if you like this post, add your favorite plugins as well.

Introduction

In this tutorial I am going to show you a simple example of how to display records using jQuery and Ajax with JSON data. I have used J2EE to supply dynamic json response however you can use same approach with any other programming language until the response from the server is in form of json.

jquery-ajax-json-demo-techyari

Step 1 : Creating the home page

Lets create our html page using using Initializr. We will modify this to suit our needs. You can also create this page from scratch if you don't want to use any css framework. We need few lines of html code to display links and corresponding records. Take a look at below code for reference

<div class="main-content">
<div class="container">
 <div class="row">
 <div class="col-md-4">
  <h3>Click on the links</h3>
  <ul>
  <li><a href="#" class="ajax-link" data-category="sports">Top 5 Sports</a></li>
  <li><a href="#" class="ajax-link" data-category="movies">Top 5 Movies</a></li>
  <li><a href="#" class="ajax-link" data-category="videogames">Top 5 Games</a></li>
  </ul>
 </div>
  <div class="col-md-8">
  <h3>Result will be displayed below using ajax</h3>
  <div class="page-content">
   <div id="0"></div>
   <div id="1"></div>
   <div id="2"></div>
   <div id="3"></div>
   <div id="4"></div>
  </div>
  </div>
 </div>
</div>
</div>

Styling the page with CSS

We will style this page using very minimal css, look at the code below :

.main-content{padding:20px;}
.lightblue{background-color:rgb(185, 224, 243)}
.page-content div{padding:5px}

Creating the Ajax request and displaying JSON records using jQuery 

In order to get the data when a user clicks on a link, we need to bind jQuery's click event with each link using the class supplied on the links. First of all we need to extract the category from link using jQuery's attribute selector, next will bind the ajax request to our ajaxController url and pass the category as query parameter,method as GET, content type as JSON and this in return will serve us with required data as response. Our ajax call contains two methods called success and failure, we will display a failure message in case of any issues while we will use the success method to display returned records using jquery's various methods and selectors. We have also provided a bit of coloring and effect using the same method.

Take a look at below code for reference :

$(document).ready(function(){
 
  var link = $('.ajax-link');
  link.click(function(){
   $('.page-content').fadeOut("fast");
   var category = $(this).attr("data-category");
   
   // Using the core $.ajax() method
   $.ajax({
       // the URL for the request
       url: "/ajaxController",
    
       // the data to send (will be converted to a query string)
       data: {
           category: category
       },
    
       // whether this is a POST or GET request
       type: "GET",
    
       // the type of data we expect back
       dataType : "json",
    
       // code to run if the request succeeds;
       // the response is passed to the function
       success: function( json ) {
           console.log(json);
          
           jQuery.each( json, function( i, val ) {
              $( "#" + i ).html(val);
              if(i%2==0){
               $( "#" + i ).addClass("lightblue");
              }
            });
           $('.page-content').fadeIn("slow");
       },
    
       // code to run if the request fails; the raw request and
       // status codes are passed to the function
       error: function( xhr, status, errorThrown ) {
           alert( "Sorry, there was a problem!" );
           console.log( "Error: " + errorThrown );
           console.log( "Status: " + status );
           console.dir( xhr );
       }
   });
  });
});


Creating the controller and getting dynamic data as JSON object

Instead of using a hardcoded json file I have created a simple Servlet wich will provide us with JSON response. I have used Google's Gson library to convert our array list to JSON.  Array list has been hard coded with few values here, however you can  get data from the database and use the same approach.


package in.techyari.demo.ajax.jqueryajax;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.http.*;
import com.google.gson.Gson;

@SuppressWarnings("serial")
public class AjaxControllerServlet extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws IOException {
  
  String category = req.getParameter("category");
  
  ArrayList result = new ArrayList();
  
  if(category.equalsIgnoreCase("sports")){
   result.add("Badminton");
   result.add("Cricket");
   result.add("Tennis");
   result.add("Football");
   result.add("Rugby");
  }else if(category.equalsIgnoreCase("movies")){
   result.add("The Godfather");
   result.add("Inception");
   result.add("Avatar");
   result.add("Titanic");
   result.add("The Fight Club");
  }else if(category.equalsIgnoreCase("videogames")){
   result.add("GTA");
   result.add("FIFA");
   result.add("Counter Strike");
   result.add("NFS");
   result.add("Angry Birds");
  }
  
  Gson gson = new Gson();
  PrintWriter writer = resp.getWriter();
  resp.setContentType("text/html");
  writer.println(gson.toJson(result));
  
 }
}

Mapping our ajaxController servlet to appropriate url

This step is only necessary if you are using J2EE as a back end to supply JSON data with last step. You can use Web 3.0 annotations as well if you are using tomcat 7 or later. To properly redirect/handle the url requested by ajax we need to update your web.xml file with our ajaxController servlet details.

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
 <servlet>
  <servlet-name>AjaxController</servlet-name>
  <servlet-class>in.techyari.demo.ajax.jqueryajax.AjaxControllerServlet</servlet-class>
 </servlet>

 <servlet-mapping>
  <servlet-name>AjaxController</servlet-name>
  <url-pattern>/ajaxController</url-pattern>
 </servlet-mapping> 
  
 <welcome-file-list>
  <welcome-file>index.html</welcome-file>
 </welcome-file-list>
</web-app>

This it it. We have successfully created a simple jQuery Ajax request and displayed few records dynamically with nice effects. I have not included pagination here as we hard coded and required only five records. In next tutorial I will show you how to handle more records from database with pagination.

Kindly like and share this tutorial if you find it useful, comment below if you wanna say something. Happy Coding ! 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.