← Back to Chapters

PHP MySQL Update Data with JS Fetch

? PHP MySQL Update Data with JS Fetch

⚡ Quick Overview

This topic demonstrates how JavaScript Fetch API can send update requests to a PHP backend that modifies records in a MySQL database.

? Key Concepts

  • JavaScript Fetch API
  • Sending JSON data via POST
  • PHP handling JSON input
  • Updating MySQL records

? Syntax / Theory

The fetch() method is commonly used with POST or PUT requests to update server-side data. PHP reads the incoming JSON using php://input and executes an SQL UPDATE query.

? Code Example(s)

? View JavaScript Fetch Code
// Send updated user data to the server using Fetch API
function updateUser() {
fetch("update.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: 1, name: "Updated Name" })
})
.then(response => response.text())
.then(data => console.log(data));
}
? View PHP Update Code
// PHP script to receive JSON and update MySQL record
$conn = new mysqli("localhost", "root", "", "testdb");
$data = json_decode(file_get_contents("php://input"), true);
$id = $data['id'];
$name = $data['name'];
$sql = "UPDATE users SET name='$name' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();

? Live Output / Explanation

Output

If the update is successful, the server responds with Record updated successfully, which is logged in the browser console.

? Interactive Example

 

? Use Cases

  • User profile updates
  • Admin dashboards
  • AJAX-based form submissions

? Tips & Best Practices

  • Always validate input before updating your database.
  • Use prepared statements to prevent SQL injection.
  • Check the browser console for fetch errors.

? Try It Yourself

  • Modify the code to update both name and email fields. Create a form where users can enter new values and update them via fetch().