Insert Data Using Ajax in PHP

Insert Data Using Ajax in PHP: This tutorial is posted for the beginner as well as experienced developers. It will help you insert form data into the MySQL Database without page refresh.

I have shared the best example using ajax, PHP & MySQL.So, You can learn How to Insert Data Using Ajax in PHP and MySQL. All the steps are explained in a simple way. Those are easy to understand. Hence, Continue reading the complete tutorials.

insert data using ajax in php

How to Insert Data Using Ajax in PHP

I have explained this tutorial with a simple form. Once you learn it, you will insert other form data without reloading the page. This script will work with different types of form data. So, It is very simple to implement in the project.

Read Also –

Fetch Data from database using Ajax

Change URL without Reloading Page Using Ajax

Load more data on Infinite Scroll Using Ajax

Before writing a Script, You must do the following things.

  • Create a project folder. otherwise, you can use the following folder structure for testing purposes.
codingstatus.com/
  |__database.php
  |__ajax-script.js
  |__php-script.php
  |__user-form.php

1. Create MySQL Database

Create MySQL database and table with the following name

  • Database Name- codingstatus ( you can use your own custom database name )
  • Table Name- usertable ( you can use  your own table name)

You can use the following query to create a table –

CREATE TABLE `usertable` (
  `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `fullName` varchar(255) DEFAULT NULL,
  `emailAddress` varchar(255) DEFAULT NULL,
  `city` varchar(255) DEFAULT NULL,
   `country` varchar(50) DEFAULT NULL,
  `created_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Connect PHP to MySQL Database

Use the following Script to connect PHP to MySQL database.

File Name – database.php

<?php
$hostname     = "localhost";
$username     = "root";
$password     = "";
$databasename = "codingstatus.com";
// Create connection
$conn = mysqli_connect($hostname, $username, $password,$databasename);
// Check connection
if (!$connection) {
    die("Unable to Connect database: " . mysqli_connect_error());
}

?>

3. Create HTML Form

Configure the following point to create HTML form –

  • Include jquery CDN to execute jquery ajax code.
  • Include external ajax script file  ajax-script.js. This file contains a custom ajax code to insert data without reloading page. Don’t worry, you will get a complete guide about this file in the next step
  • Create an HTML form with the following form attribute & input fields
    • <form> – This tag must have id="userForm"method="post"
    • Full Name – It should be text input and should have name="fullName" attribute.
    • Email Address – It should be an email input field and should have  name="email" attribute.
    • City – It should be a text input field and should have  name="city" attribute
    • Country – It should be a text input field and should have  name="country" attribute
    • Submit Button – It should be a button.

File Name – user-form.php

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!--====form section start====-->
<div class="user-detail">
    <h2>Insert User Data</h2>
    <p id="msg"></p>
    <form id="userForm" method="POST">
          <label>Full Name</label>
          <input type="text" placeholder="Enter Full Name" name="fullName" required>
          <label>Email Address</label>
          <input type="email" placeholder="Enter Email Address" name="emailAddress" required>
          <label>City</label>
          <input type="city" placeholder="Enter Full City" name="city" required>
          <label>Country</label>
          <input type="text" placeholder="Enter Full Country" name="country" required>
          <button type="submit">Submit</button>
    </form>
        </div>
</div>
<!--====form section start====-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="ajax-script.js"></script>
</body>
</html>

You can use the following CSS code to design user form –

<style>
* {
  box-sizing: border-box;}
.user-detail {
    height: 100vh;
    border: 2px solid #f1f1f1;
    padding: 16px;
    background-color: white;
    width: 30%;}
input{
  width: 100%;
  padding: 15px;
  margin: 5px 0 22px 0;
  display: inline-block;
  border: none;
  background: #f1f1f1;}
input[type=text]:focus, input[type=password]:focus {
    background-color: #ddd;
    outline: none;}
button[type=submit] {
    background-color: #434140;
    color: #ffffff;
    padding: 10px 20px;
    margin: 8px 0;
    border: none;
    cursor: pointer;
    width: 100%;
    opacity: 0.9;
    font-size: 20px;}
label{
  font-size: 18px;;}
button[type=submit]:hover {
  background-color:#3d3c3c;}
  #msg{
    color: green;
    font-size: 16px;
  }
</style>

 

4. INSERT Data without Reloading Page Using Ajax

You have to configure the following steps to insert data without reloading the page –

  • First of all, apply submit event on the HTML form with id #userForm.
  • Define e.preventDefault() to submit form data without reloading the page.
  • Send POST request to PHP code for inserting data into the database.
  • Declare URL php-script.php. This URL contains PHP code. Don’t worry, It will explain in the next step.
  • Display success or error message  in div with id #msg.

Full Name – ajax-script

$(document).on('submit','#userForm',function(e){
        e.preventDefault();
       
        $.ajax({
        method:"POST",
        url: "php-script.php",
        data:$(this).serialize(),
        success: function(data){
        $('#msg').html(data);
        $('#userForm').find('input').val('')

    }});
});

5. Insert Data Using PHP

To insert data into MySQL database, configure the following steps –

  • First, Include database connection file database.php
  • Assign connection variable $conn to a new variable $db
  • Create a custom function insert_data(). This function will insert form data into database.
  • Then call insert_data()  if all the fields are not empty.
  • Also, Create another custom function legal_input() to convert illegal input to legal input.

File Name – php-script.php

<?php
include('database.php');
$db=$conn;// database connection  

//legal input values
 $fullName     = legal_input($_POST['fullName']);
 $emailAddress = legal_input($_POST['emailAddress']);
 $city         = legal_input($_POST['city']);
 $country      = legal_input(md5($_POST['country']));
   
if(!empty($fullName) && !empty($emailAddress) && !empty($city) && !empty($country)){
    //  Sql Query to insert user data into database table
    Insert_data($fullName,$emailAddress,$city,$country);
}else{
 echo "All fields are required";
}
 
// convert illegal input value to ligal value formate
function legal_input($value) {
    $value = trim($value);
    $value = stripslashes($value);
    $value = htmlspecialchars($value);
    return $value;
}

// // function to insert user data into database table
 function insert_data($fullName,$emailAddress, $city, $country){
 
     global $db;

      $query="INSERT INTO usertable(fullName,emailAddress,city,country) VALUES('$fullName','$emailAddress','$city','$country')";

     $execute=mysqli_query($db,$query);
     if($execute==true)
     {
       echo "User data was inserted successfully";
     }
     else{
      echo  "Error: " . $sql . "<br>" . mysqli_error($db);
     }
 }


?>

Tutorial Summary

Dear Developers, I hope This tutorial is helpful and you have understood the above concept. Now you can easily implement another Insert data.

If you have any doubts or questions, you can ask me directly through the below comment box. I will definitely reply as soon as possible.

Even you can suggest topics or ideas related to web technology to share tutorials. and share this tutorial with your friends those who want to learn it.

Thanks for giving the time to this tutorial…

Leave a Comment