← Back to Chapters

PHP AJAX Insert Records in Database

? PHP AJAX Insert Records in Database

? Quick Overview

AJAX allows web pages to communicate with the server asynchronously. Using PHP and AJAX together enables inserting database records without refreshing the page, improving user experience in modern web applications.

? Key Concepts

  • Asynchronous communication using AJAX
  • Client-side form submission
  • Server-side processing with PHP
  • Database insertion using MySQL

⚙️ Syntax & Theory

The browser sends form data using an AJAX request. PHP receives the request, validates and sanitizes the input, then inserts the record into the database and returns a response.

? Code Examples

HTML + JavaScript (AJAX)

? View Code Example
// HTML form and AJAX submission logic
<form id="dataForm">
<label>Name:</label>
<input type="text" id="name"><br><br>
<label>Email:</label>
<input type="text" id="email"><br><br>
<button type="submit">Submit</button>
</form>
<div id="response"></div>

document.getElementById("dataForm").addEventListener("submit",function(e){
e.preventDefault();
var name=document.getElementById("name").value;
var email=document.getElementById("email").value;

var xhr=new XMLHttpRequest();
xhr.open("POST","insert.php",true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onload=function(){
document.getElementById("response").innerHTML=xhr.responseText;
};
xhr.send("name="+name+"&email="+email);
});

PHP Script (insert.php)

? View Code Example
// PHP script to insert form data into MySQL
<?php
$conn=new mysqli("localhost","username","password","database");
if($conn->connect_error){
die("Connection failed");
}
$name=mysqli_real_escape_string($conn,$_POST["name"]);
$email=mysqli_real_escape_string($conn,$_POST["email"]);
$sql="INSERT INTO users(name,email) VALUES('$name','$email')";
if($conn->query($sql)){
echo "Record inserted successfully";
}else{
echo "Error inserting record";
}
$conn->close();
?>

? Live Output / Explanation

When the form is submitted, the data is sent to the server without page reload. The server inserts the record and sends a success or error message back to the page.

? Interactive Flow

User → Form → AJAX Request → PHP Script → Database → Response Message

? Use Cases

  • User registration forms
  • Feedback or contact forms
  • Admin dashboards

✅ Tips & Best Practices

  • Always sanitize and validate user input
  • Use prepared statements for better security
  • Handle AJAX errors gracefully

? Try It Yourself

  • Add phone number field
  • Send data as JSON
  • Display inserted records dynamically