Editing database records by user using PHP & Ajax

Update one field with fetch()

Keep the record ID and new mark as data, validate both on the server, and return JSON from the update endpoint. The browser can then update only the changed cell without reloading the table.

async function updateMark(id, mark) {
    const response = await fetch('display-record-edit-ajaxck.php', {
        method: 'POST',
        headers: {'Accept': 'application/json'},
        body: new URLSearchParams({id, mark})
    });

    const result = await response.json();
    if (!response.ok) throw new Error(result.message ?? 'Update failed');
    document.querySelector(`[data-mark-id="${id}"]`).textContent = result.mark;
}
<?php
$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
$mark = filter_input(INPUT_POST, 'mark', FILTER_VALIDATE_INT);

if (!$id || $mark === false || $mark < 0 || $mark > 100) {
    http_response_code(422);
    echo json_encode(['message' => 'Invalid id or mark']);
    exit;
}

$stmt = $pdo->prepare('UPDATE student SET mark = :mark WHERE id = :id');
$stmt->execute(['mark' => $mark, 'id' => $id]);

echo json_encode(['id' => $id, 'mark' => $mark]);
?>

The public demo validates and returns the edited value without changing production data. In the downloadable database project, the PHP endpoint performs the prepared UPDATE. For a production editing interface, also require authentication, per-record authorization and CSRF protection.

We will display all the student records and give the option to the user to edit the mark obtained by each student. Here user will update the mark and same will be displayed after updation of the record.

Why use Ajax

For better user experience we will update the record with new mark without reloading the page by using Ajax. Here each record will have one Edit button. On click of the update button we will display one text box with default mark ( record data ) inside it. User can change the data and click the Updation button. Through Ajax we will post the updated mark to our PHP script to update the MySQL student table record. Based on the success of the updation process we will display a message and updated mark.

Basic understanding of Ajax is required for this tutorial

How the script work.

Records with edit option script
We display the records in a tabular manner. Each record will have mark at right most column with one button to edit. See the demo

Demo of Record display with edit option

We have displayed our records by using Query and using SQL limit command to display only 10 records. ( you can extended as many numbers you want ) . Each student mark we kept in a separate div tag. Here the id of the div tag is the id of the student record ( which is unique ). Example 3, 14, 6 etc. To manage the button we used same id with ‘s’ as prefix. Example s4, s12 etc.
require "config.php"; // MySQL connection string
echo "<div id="msgDsp" STYLE="position: absolute; right: 0px; top: 10px;left:800px;text-align:left; FONT-SIZE: 12px;font-family: Verdana;border-style: solid;border-width: 1px;border-color:white;padding:0px;height:20px;width:250px;top:10px;z-index:1"> Edit mark </div>";

$count="SELECT name,id,class,mark,sex FROM student LIMIT 10";

$i=1;

echo "<br><br><br><table class='t1'><tr><th>Name</th><th>Class</th><th>Sex</th><th>Mark</th><th>Edit</th></tr>";
foreach ($dbo->query($count) as $row) {
$m=$i%2;
$sid='s' . $row['id'];
echo "<tr class='r$m'><td> $row[name] </td><td> $row[class]  </td><td> $row[sex] </td><td>  <div id=$row[id] STYLE="width:140px;">$row[mark]</div></td><td><input type=button id=$sid value='Edit' onclick=edit_field($row[id])></td></tr>";
$i=$i+1;
}
echo "</table>";

User clicks the Edit button

When the learner clicks Edit, create the input and Update button with DOM methods rather than assembling an HTML string. Read the current mark with textContent, keep the record ID in a data attribute, and pass the two values to the Fetch function shown above.

function editField(id) {
    const cell = document.querySelector(`[data-mark-id="${id}"]`);
    if (!cell) return;

    const currentMark = cell.textContent.trim();
    const input = document.createElement('input');
    input.type = 'number';
    input.min = '0';
    input.max = '100';
    input.value = currentMark;

    const button = document.createElement('button');
    button.type = 'button';
    button.textContent = 'Update';
    button.addEventListener('click', () => updateMark(id, input.value));

    cell.replaceChildren(input, button);
}

Displaying status messages

Use one status element for success or validation messages. Assign plain text with textContent, then clear it with a callback-based timer as shown in the response-handling example below.

Backend PHP script to validate the record update

The endpoint should accept POST only, validate both fields before any database write, and return JSON. The public demo uses the same validation contract without modifying production data.

<?php
header('Content-Type: application/json; charset=UTF-8');

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    http_response_code(405);
    echo json_encode(['message' => 'POST requests only.']);
    exit;
}

$id = filter_var($_POST['id'] ?? null, FILTER_VALIDATE_INT, [
    'options' => ['min_range' => 1],
]);
$mark = filter_var($_POST['mark'] ?? null, FILTER_VALIDATE_INT, [
    'options' => ['min_range' => 0, 'max_range' => 100],
]);

if ($id === false || $mark === false) {
    http_response_code(422);
    echo json_encode(['message' => 'Enter a valid record ID and a mark from 0 to 100.']);
    exit;
}
?>
If all data validations are cleared then we will go for updating the record with new data ( mark ).
require "config.php"; // MySQL connection string
$count=$dbo->prepare("update student set mark=:mark WHERE id=:id");
$count->bindParam(":mark",$mark,PDO::PARAM_INT,3);
$count->bindParam(":id",$id,PDO::PARAM_INT,3);
After this we will be using Json to return the string of data to our main page to display the updated record.
$a = array('id'=>$id,'mark'=>$mark);
$a = array('data'=>$a,'value'=>array("status"=>"$status","message"=>"$message"));
echo json_encode($a); 

Receiving the updated record and displaying

The Fetch request returns JSON. Read the JSON, check the HTTP status, then update only the text that changed. Use textContent for plain values and a function callback with setTimeout() when clearing the status message.
const result = await response.json();
if (!response.ok) {
    throw new Error(result.message ?? 'Update failed');
}

const markCell = document.querySelector(`[data-mark-id="${result.id}"]`);
const messageBox = document.getElementById('msgDsp');

if (markCell) markCell.textContent = String(result.mark);
if (messageBox) {
    messageBox.textContent = result.message ?? 'Record updated.';
    setTimeout(() => {
        messageBox.textContent = '';
    }, 2000);
}
If the updation has failed then we will keep showing the same update option and change the border color of the display message box to red while showing the failure message to user. We can show one reset button or close button so user can reload the page with fresh data.

Part II : Edit all the columns of a record

download script
PHP MySQL Collecting single record from MySQL PHP Code generator for PDO & mysqli


Subscribe to our YouTube Channel here



plus2net.com







kishan

27-05-2014

the above demo is nice.... it is editing only one field i want entire fields,,,for example firstname,lastname,email fields in a table format having only one edit button....I need help...thanks
smo

13-11-2014

Second part is on editing more fields.
rajeev

02-12-2014

click on text and get value of each row record click on text and get value of each row record
renu

01-10-2015

don't have idea about pdo i generlly use mysqli........ if possible send me the above example in mysqli
Robert

13-05-2017

I have read the tutorial, but it is missing the part that explains how to "use" and how to "interpreter" the tutorial itself. It is excessively concise, maybe it is for gurus, because if could it be for newbies ... well it looks to me they are missing too many steps.
Regards
smo1234

19-05-2017

Third part of this tutorial is added by using JQuery. This part is kept in display-edit3 folder. In this MySQLI is used in place of PDO. Those who don't want to use PDO can use this part for MySQLi with minor changes. We tried to explain more for better understanding of all.
David

22-01-2019

Can you help me please ? onclick=edit_field($row[id]) does nothing.
My table data is displayed but cannot be edited !
Is there an update to the script ?
Thank you.




PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer