I'm trying to delete records from the DB by their ID. The code works as it should but the problem is the ID is coming up in the URL, which from my knowledge it's unsafe.
URL: "http://localhost/Project/includes/delete.php?id=27"
I have used prepared statement to delete the records but the problem comes from the button. IS there any other approach to the one I'm already using to make it safe?
Here is the code:
while($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>' . $row['row1'] . '</td>';
echo '<td>' . $row['row2'] . '</td>';
echo '<td>' . $row['row3'] . '</td>';
echo '<td><a href="delete.php?id=' . $row['id'] . '">Delete</a></td>';
echo '</tr>';
}
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$id = $_GET['id'];
if ($stmt = $mysqli->prepare("DELETE FROM table WHERE id = ? LIMIT 1")) {
$stmt->bind_param("i", $id);
$stmt->execute();
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows);
$stmt->close();
}
}
Basically I'd like to the make the whole row clickable, whenever the user clicks on the row to delete the records, rather than using the buttons. However, my big challenge is how not to show its ID in the URL.
Any help is highly appreciated.
Thank you
To do this you could place a form in the last table cell:
The form uses a hidden input for your id value.
In your PHP you would then change to the
$_POST
array,$_POST['id']
Set the
Id
in$_SESSION
and you can pass it between pages.OR
You can do it with ajax
Add this script in page where above code is located ;
create a delete.php in root and it will be like
With Ajax, your page won't be refreshed and data will be deleted from database and deleted row will be hidden from user
Encode the ID with a two-way encryption, so that it is 'sent' encoded, and decoded to use.