Monday, September 9, 2019

Inserting data into MySQL database using PHP, AJAX, Bootstrap and JQuery


Introduction
In this article, I will demonstrate how to insert data into MySQL database using PHP, Ajax, Bootstrap and JQuery.
Here are the necessarily steps:
Step 1. Creating the database table: employee table in MySQL database


CREATE TABLE IF NOT EXISTS `employee` ( 
  `id` int(11) NOT NULL AUTO_INCREMENT, 
  `username` text NOT NULL, 
  `position` text NOT NULL, 
  PRIMARY KEY (`id`) 
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=23 ;

Step 2. Creating index.php
Here, I use cdn link to use bootstrap.min.css, bootstrap.min.js, jquery.min.js and font-awesome.min.css. I use the minified version of all required files. 


<head>
 <title>Employee Management System</title>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" 
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" 
crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

 <script type="text/javascript" src="main.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
   <a class="navbar-brand" href="#">Employee Registratoin Form</a>
   <button class="navbar-toggler" type="button" data-toggle="collapse" 
data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" 
aria-label="Toggle navigation">
     <span class="navbar-toggler-icon"></span>
   </button>
   
</nav>
  <br><br>
  <div class="container">
   <div class="card mx-auto" style="width: 18rem;">
    <div class="card-header">Register</div>
    <div class="card-body">
      <form id="register_employee_form" onsubmit="return false" autocomplete="off">
     <div class="form-group">
       <label for="username">User Name</label>
       <input type="text" class="form-control" name="username" id="username" 
       aria-describedby="emailHelp" placeholder="Enter Username">
       <small id="u_error" class="form-text text-muted"></small>
     </div>
     <div class="form-group">
       <label for="postion">Job Postion</label>
       <input type="text" class="form-control" name="position" id="position" 
         aria-describedby="emailHelp" placeholder="Enter Job Postion">
       <small id="p_error" class="form-text text-muted"></small>
     </div>
     <button type="submit" name="user_register" id="btn_user_register" 
       class="btn btn-primary"><i class="fa fa-user">&nbsp;</i>Register</button>
   </form>
   <div id="return"></div>
    </div>
  </div>
</body>
</html>


The page looks as follows:



Step 3. Creating the file that handles the ajax request: main.js
$(document).ready(function() {

 $('#btn_user_register').click(function() {
            
    var fullname = $("#username").val();
    var jobposition = $("#position").val();
        
    if(fullname.length == 0 || jobposition.length == 0){
            
       $('form').trigger("reset");
       $('#return').fadeIn().html("<h5 class='text-danger'>All fields are required</h5>");
           
     }else{
       $('#return').html("<small></small>");
       $.ajax({
            url: "insertEmployee.php",
            method:"POST",
            data: $('#register_employee_form').serialize(),
            success: function(data) {
            $('form').trigger("reset");
            $('#return').fadeIn().html(data);
                    setTimeout(function() {
                        $('#return').fadeOut("slow");
                    }, 1500);
 
                }
            });
        }
        
    });

});


Step 4. Here in the final step, I will create the PHP file that inserts the data to the database: insertEmployee.php




<?php
   $conn = mysqli_connect("localhost", "root", "", "ajaxtestdb"); 
   if(isset($_POST["username"])){ 
   $username = mysqli_real_escape_string($conn, $_POST["username"]); 
   $job_position = mysqli_real_escape_string($conn, $_POST["position"]); 
   $query = "INSERT INTO employee(username, position) VALUES ('".$username."',   
            '".$job_position."')"; 
       if(mysqli_query($conn, $query)){ 
          echo '<p style="color:green;">Data Inserted Successfully..</p>'; 
       } else{
     echo '<p>Data Insertion Failed..</p>';
    }
  } 
?>

1 comment: