PHP - SPLessons

Save data using Ajax and PDO with Bootstrap and ValidationEngine

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


              – –    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


              – –    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='|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>
        <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 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 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 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
          <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 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 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 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 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><!-- 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 class="table-responsive result" style="display:none">
        <div class="page-header">
  		  <h2>Your details :</h2>
       <table class="table">
           <th>First Name</th>
           <th>Last Name</th>
           <th>Date of Birth</th>
           <th>User Name(Email)</th>
            <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>
     </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() {
	   var date = new Date();
		    $('.datepicker').datepicker({startDate:false,format:'yyyy-mm-dd',autoclose: true,todayHighlight:true}); 
			$("#register-form").on("submit",function(e) {
				if($("#register-form").validationEngine('validate')) {
			  	    var form_data = $( "form" ).serialize();
					    $.post( "insert.php",{form_values : form_data},function( data ) {
						var Data =  jQuery.parseJSON(data);
								  $(".success_msg").show(200,function() {
	   } 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

 `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,


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


    $username = "root";
    $password = "";
    $host = "localhost";
    $dbname = "save-data-using-ajax-and-pdo-with-bootstrap";
	$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');  
        $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);     


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


	 $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;

	    $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 (
		  $query_insert = $db->prepare( $sql_insert );
          $result_insert = $query_insert -> execute(array(
								      ':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
			           FROM users
                       id = :id";
			  $query_select = $db->prepare( $sql_select );
			  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";