← Back to Chapters

PHP MySQL Insert Data with Fetch API

? PHP MySQL Insert Data with Fetch API

? Quick Overview

The JavaScript Fetch API allows sending form data asynchronously to a PHP backend. PHP then inserts this data into a MySQL database using prepared statements, improving performance and user experience by avoiding page reloads.

? Key Concepts

  • Fetch API for asynchronous requests
  • FormData for automatic POST encoding
  • PHP PDO with prepared statements
  • Server-to-client response handling

? Syntax & Theory

The browser captures form submission, prevents default reload, sends data using Fetch, and PHP processes the request securely using PDO before returning a response.

? Code Example

? View Code Example
// HTML form with Fetch API
<!DOCTYPE html>
<html>
<body>
<h3>Add New User</h3>
<form id="userForm">
<input type="text" name="name" placeholder="Enter name"><br>
<input type="email" name="email" placeholder="Enter email"><br>
<button type="submit">Submit</button>
</form>

<script>
document.getElementById("userForm").addEventListener("submit",function(e){
e.preventDefault();
let formData=new FormData(this);
fetch("insert.php",{method:"POST",body:formData})
.then(res=>res.text())
.then(data=>alert(data))
.catch(err=>console.error(err));
});
</script>
</body>
</html>

// PHP script using PDO
<?php
if($_SERVER["REQUEST_METHOD"]==="POST"){
$name=$_POST["name"]??"";
$email=$_POST["email"]??"";
try{
$pdo=new PDO("mysql:host=localhost;dbname=testdb","root","");
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$stmt=$pdo->prepare("INSERT INTO users(name,email) VALUES(:name,:email)");
$stmt->bindParam(":name",$name);
$stmt->bindParam(":email",$email);
$stmt->execute();
echo "User inserted successfully!";
}catch(PDOException $e){
echo "Error: ".$e->getMessage();
}
}
?>

? Live Output / Explanation

When the form is submitted, the data is sent without reloading the page. PHP inserts the record into the database and sends a success message back, which is displayed using an alert.

? Interactive Idea

You can enhance this example by displaying success messages inside the page instead of alerts or by animating a loading spinner during submission.

? Use Cases

  • User registration forms
  • Contact forms
  • Admin dashboards
  • AJAX-based CRUD applications

✅ Tips & Best Practices

  • Always validate and sanitize data on the server
  • Use prepared statements to prevent SQL injection
  • Return JSON responses for scalable applications

? Try It Yourself

  • Add more input fields like age or city
  • Return JSON and parse it in JavaScript
  • Add client-side validation before submitting