PHP - SPLessons

Save data using Ajax and PDO with Boot...

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Save data using Ajax and PDO with Bootstrap and ValidationEngine

Save data using Ajax and PDO with Bootstrap and ValidationEngine

Hi Friends , Today in this article we are going to explain about how to build a small project in PHP with beautiful responsive form, power full front end validations and secure way of storing data into database.  With the following demo Save data using Ajax and PDO with Bootstrap and ValidationEngine we will see how easy it to develop a project in PHP.

 

 


With is this article you can learn the following things within 15 minutes :

Creating a beautiful responsive form with bootstrap
 
How to use validation to the responsive form with the help of power full jQuery validation engine
 
How to use Ajaxs to submit the form with out refreshing the page
 
How to get a database connection with PDO
 
How to insert the form data into database with PDO
 
How to avoid the SQL injections with the help of PDO
 
Finally how to send the JSON response to client request from the server
 

 

What is Bootstrap ?

Bootstrap is an  open-source framework developed by Twitter  for front end developers to make responsive and beautiful  websites in less time . It is a combination of HTML , CSS and JavaScript and it is support to both HTML5 and CSS3 .

What is Ajax ?

Ajax short for(Asynchronous JavaScript and XML) is an Client side Script to interact with the server without reloading a page.

What is PDO ?

PDO  short for(PHP Data Objects) today many PHP developers are using MySQL or MySQLi extensions but there’s another way or better way i.e., PDO (PHP Data Objects). PDO is an Object Oriented . It supports to prepare and excute statements . These statements are give more security for our web applications and also for transcations .PDO supports to many databases (not only to MySQL). PDO is recommend to every one because MySQL deprecated in future.  So  today in this article we are using PDO for inserting data into database.

Description :

First,In this article  we create a responsive form with bootstrap  then  we validate the form fields with jQuery ValidateEngine  plug-in  and we post the form values to the server using  $.post() method I mean Ajaxs call. Now, we get the all form values in server.  We will insert the form data into a database. If you see here, we are using database connection with PDO. We inserted form values into a database by using PDO and get last_insert_id for confirmation of successfull insertion of data into database. Finally, we just fetched the last inserted data and send to client browser in very popular JSON format to display results you can skip this step because we just want to show how we can able to send response to client request in JSON format.

This article contains  three  PHP files and two folders are js and css

              – –  db.php
              – –  insert.php
              – –  Save-data-using-Ajax-and-PDO-with-Bootstrap.php

js

              – –    jquery.min.js
              – –   bootstrap.min.js
              – –   bootstrap-datepicker.js
              – –   jquery.validationEngine-en.js
              – –   jquery.validationEngine.js
              – –   Save-data-using-Ajax-and-PDO-with-Bootstrap.js

css

              – –    bootstrap.min.css
              – –    datepicker.css   
              – –    validationEngine.jquery.css  
              – –   Save-data-using-Ajax-and-PDO-with-Bootstrap.css

Step1 :

Add below code in HTML head


<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/datepicker.css">
<link rel="stylesheet" href="css/validationEngine.jquery.css">
<link href='http://fonts.googleapis.com/css?family=PT+Serif+Caption|Source+Serif+Pro' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/Save-data-using-Ajax-and-PDO-with-Bootstrap.css">

 

Step2 :
We create a responsive registration form with bootstrap Add below code in HTML body

<div class="container">
      <div class="row">
        <div class="registration_form">
        <div class="page-header">
  		  <h1>Save data using  Ajax and PDO with Bootstrap and ValidationEngine</h1>
	    </div>
        <form class="form-horizontal" role="form" method="post" action="#" id="register-form">
 		  
          <div class="form-group">
   			  <label for="firstName" class="col-sm-2 control-label">First Name:</label>
    	    <div class="col-sm-6">
              <input type="text" name="firstName" class="form-control" id="firstName" placeholder="First Name"   		data-validation-engine="validate[required]" data-errormessage-value-missing="First Name is required!" >
            </div>
          </div>
          
          <div class="form-group">
   			  <label for="lastName" class="col-sm-2 control-label">Last Name:</label>
    	    <div class="col-sm-6">
              <input type="text" name="lastName" class="form-control" id="lastName" placeholder="Last Name"  data-validation-engine="validate[required]" data-errormessage-value-missing="Last Name is required!" >
            </div>
          </div>
          
          
           <div class="form-group">
             <label for="" class="col-sm-2 control-label">Gender:</label> 
           <div class="col-sm-6">
             <label class="radio-inline">
  				<input type="radio" name="gender" id="gender1" value="male" data-validation-engine="validate[required]"
                data-errormessage-value-missing="Please Select Male or Female">Male
			 </label>
			<label class="radio-inline">
  				<input type="radio" name="gender" id="gender2" value="female" data-validation-engine="validate[required]"  data-errormessage-value-missing="Please Select Male or Female">Female
			</label>
			</div>
        </div>
          
          <div class="form-group">
   			  <label for="dob" class="col-sm-2 control-label">DOB:</label>
    	    <div class="col-sm-6">
              <input type="text" name="dob" class="form-control datepicker" id="dob" placeholder=" Date of Birth" data-validation-engine="validate[required]" data-errormessage-value-missing="Please Select your Date of Birth">
            </div>
          </div>
          
          <div class="form-group">
   			  <label for="userName" class="col-sm-2 control-label">User Name:</label>
    	    <div class="col-sm-6">
              <input type="email" name="userName" class="form-control" id="userName" placeholder="Email" data-validation-engine="validate[required,custom[email]]" data-errormessage-value-missing="Your Email is required!" >
            </div>
          </div>
  
         <div class="form-group">
             <label for="passwd" class="col-sm-2 control-label">Password:</label>
           <div class="col-sm-6">
      		 <input type="password" name="passwd" class="form-control" id="passwd" placeholder="Password" 			  data-validation-engine="validate[required] text-input" data-errormessage-value-missing="Password is required!">
           </div>
         </div>
         
         
         <div class="form-group">
             <label for="confirm_passwd" class="col-sm-2 control-label">Confirm-Password:</label>
           <div class="col-sm-6">
      		 <input type="password" name="confirm_passwd" class="form-control" id="confirm_passwd" placeholder="Confirm Password" data-validation-engine="validate[required,equals[passwd]] text-input" data-errormessage-value-missing="Confirm Password is required!">
           </div>
         </div>
         
         
        <div class="form-group">
          <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-primary" id="register" name="submit">Submit</button>
          </div>
       </div>
	
     </form>
     </div><!-- end for class "registration_form" -->
     
     
     <div class="alert alert-success alert-dismissible success_msg" role="alert">
             <button type="button" class="close" data-dismiss="alert">
                <span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
       <strong>Well done!</strong>Your details submitted Succesfully .
</div>
     
     
     
     <div class="table-responsive result" style="display:none">
        <div class="page-header">
  		  <h2>Your details :</h2>
	    </div>
       <table class="table">
         <tr>
           <th>First Name</th>
           <th>Last Name</th>
           <th>Gender</th>
           <th>Date of Birth</th>
           <th>User Name(Email)</th>
           <th>Password</th>
         </tr>
       <tr>
            <td id="First_name"></td>
            <td id="Last_name"></td>
            <td id="Gender"></td>
            <td id="Dob"></td>
            <td id="User_name"></td>
            <td id="Password"></td>
       </tr>
    
         </table>
     </div> <!-- end for class "result" -->
     
     </div><!-- end for class "row" -->
   </div><!-- end for class "container" -->

 

Step3 :

Add JavaScript  files end of  body tag in HTML to improve the performance of  our Web application

Add below code in end of HTML body

<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap-datepicker.js"></script>
<script type="text/javascript" src="js/jquery.validationEngine-en.js"></script>
<script type="text/javascript" src="js/jquery.validationEngine.js"></script>
<script type="text/javascript" src="js/Save-data-using-Ajax-and-PDO-with-Bootstrap.js"></script>

 

Step4 :

We validate all the all fields with jQuery ValidationEngine  after that we send the values to server with $.post () function . In Server side we processing those  values and insert the data into database by using PDO . we got an JSON format data in Success function of Ajax .Finally, We converted JSON format data into JavaScript Object notation.

Add below code in JavaScript

// JavaScript Document
$(document).ready(function() {
	   
	   jQuery("#register-form").validationEngine();
	   
	   var date = new Date();
            date.setDate(date.getDate()-1);
		    $('.datepicker').datepicker({startDate:false,format:'yyyy-mm-dd',autoclose: true,todayHighlight:true}); 
	        
			$("#register-form").on("submit",function(e) {
			    
				e.preventDefault();
			    
				if($("#register-form").validationEngine('validate')) {
			  	    var form_data = $( "form" ).serialize();
					    $.post( "insert.php",{form_values : form_data},function( data ) {
						var Data =  jQuery.parseJSON(data);
						$(".registration_form").hide(200);
								  
								  
								  $(".success_msg").show(200,function() {
									 $(".result").show();
							         $("td#First_name").html(Data[0].First_name);
								     $("#Last_name").html(Data[0].Last_name);
								     $("#Gender").html(Data[0].Gender);
								     $("#Dob").html(Data[0].Dob);
								     $("#User_name").html(Data[0].User_name);
							         $("#Password").html(Data[0].Password);
								  });
				  });
		  
	   } else {
		    return false;
		}
	   });
		
});

Step5 :

We create a users table with nine  columns(id(Primary Key),First_name, Last_name, Gender, Dob, User_name, Password, Created_Date, Last _Modified) in save-data-using-ajax-and-pdo-with-bootstrap database to store form values in users table

Create ‘users’ table


CREATE TABLE IF NOT EXISTS `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `First_name` varchar(255) NOT NULL,
 `Last_name` varchar(255) NOT NULL,
 `Gender` varchar(20) NOT NULL,
 `Dob` date NOT NULL,
 `User_name` varchar(255) NOT NULL,
 `Password` varchar(100) NOT NULL,
 `Created_date` datetime NOT NULL,
 `Last_modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

 

Step6 :

We create a db.php file  to connect with a database by using PDO .In line 12 we create a PDO object  to connect with a database.

Create db.php file

<?php

    $username = "root";
    $password = "";
    $host = "localhost";
    $dbname = "save-data-using-ajax-and-pdo-with-bootstrap";
	
	$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');  
	
	try
    {
        $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8",$username, $password ,$options);
    }
    catch(PDOException $ex)
    {
        die("Failed to connect to the database: " . $ex->getMessage());
    } 
   // an error.  This allows us to use try/catch blocks to trap database errors.
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);     
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);   
	
?>

 

Step7 :

We create insert.php file to get the values from client side then Processing the values and  inserted into database. Finally , we fetch the inserted data from database by using last_insert_id to give a JSON response to client request.

Create insert.php file


<?php

if(isset($_POST["form_values"]))
{
	 $form_data = urldecode($_POST["form_values"]);
	 
	 preg_match_all('#(\w+)=([^&=]*)(?:&|$)#', $form_data, $matches, PREG_SET_ORDER); 
     $result = array();
	   $i = 0;    
          foreach ($matches as $m) {
             list(, $key, $value) = $m;
          if (!strlen($value)) { 
             $i = (int)$key;
          } else {
           $result[$i][$key] = $value;
	     }
}

        require_once("db.php");
	 
	    $firstName = $result[0]["firstName"];
	    $lastName = $result[0]["lastName"];
	    $gender = $result[0]["gender"];
	    $dob = $result[0]["dob"];
	    $userName = ($result[0]["userName"]);
	    $password = md5($result[0]["passwd"]);
	 
	 
	    $sql_insert = "INSERT INTO users (First_name, Last_name, Gender, Dob, User_name,Password,Created_date,Last_modified) VALUES (
                :firstName,
                :lastName,
                :gender,
                :dob,
                :userName,
				:password,
                :Created_date,
                :Last_modified
            )"; 
	 
	try
	    {
	      
		  $query_insert = $db->prepare( $sql_insert );
          $result_insert = $query_insert -> execute(array(
		                              ':firstName'=>$firstName, 
								      ':lastName'=>$lastName,
								      ':gender'=>$gender, 
								      ':dob'=>$dob, 
								      ':userName'=>$userName, 
								      ':password'=>$password,
								      ':Created_date'=>date("Y-m-d H:i:s"),
								      ':Last_modified'=>date("Y-m-d H:i:s")));
	 
	    }
	 
	catch(PDOException $ex)
        {
            // Note: On a production website, you should not output $ex->getMessage().
            // It may provide an attacker with helpful information about your code.
            die("Failed to run query: " . $ex->getMessage());
        } 
    if($result_insert) {
		     
			$last_insert_id = $db->lastInsertId();
			
			$sql_select = "SELECT
                            First_name,
							Last_name,
							Gender,
							Dob,
							User_name,
							Password,
							Created_date,
							Last_modified
			           FROM users
                       WHERE
                       id = :id";
		    
			
			try 
			{
			
			  $query_select = $db->prepare( $sql_select );
			  $query_select->execute(array(':id'=>$last_insert_id));
			  $results=$query_select->fetchAll(PDO::FETCH_ASSOC);
			  $json=json_encode($results);
			  echo $json;
			 
			}
			
			catch(PDOException $ex)
        	{
                 // Note: On a production website, you should not output $ex->getMessage().
                 // It may provide an attacker with helpful information about your code.
                 die("Failed to run query: " . $ex->getMessage());
             } 
			
		      //echo "You are successfully registered.";
	  }  else {
		    echo "error occured";
	 }
}

?>