Search code examples
phphtmlformspostsubmission

PHP form validation server-side for updating an existing row in a database


How do I validate the row ID is the correct one to be updated? I think I may be taking the wrong approach entirely as this doesn't seem to be right.

I'm storing my row id in a session. As well as sending it in a hidden input. Then its get check in validate.php. This works fine but using sessions removes the ability to edit multiple pages in the same browser session. I'm a bit confuse on how to validate a row ID.

Database Table

id - name
1 - Apple
2 - Orange

Each row has its own page with a edit form

<?php session_start(); $_SESSION['id'] = X; ?>
<form action="/validate.php" method="post">
 <input type="hidden" name="id" value="X">
 <input type="text" name="name" value="">
 <input type="submit" value="submit">
</form>

validate.php

session_start(); 
$session_id = $_SESSION['id'];
$name = $_POST['name'];
$id = $_POST['id'];

if ($session_id == $id){
 updateRow($name,$id); // send args to another function to do the sql logic.
} else {
 var_dump('mis-match id');
}

Solution

  • Well I could suggest that, why create a json format session['IDs'].. which stores different multiple IDs.. JSON has a key value pair, therefore make an identifier in your form, like in a hidden input, to retrieve their corresponding value in your validate.php... Or if this is even hard, don't store ID in a session...