Delete record using PHP
Subject: Web development using PHP and MySQL
We use the DELETE SQL statement to delete record from a table.
syntax
DELETE FROM table_name WHERE id = record_id
Example
DELETE FROM feedback WHERE id = 3
However the record_id e.g 3 will not be hardcoded like this, just as we did with edit, we will introduce a "Delete" link and the link will send the id number to the code for deleting.
Here is the code (I have remove the pagination section to make the code focus on deleting, I will provide a GitHub link below to download the all code)
feedback_table_paginate_update.php
Company Feedback
FEEDBACK LIST
NAME |
EMAIL |
COMMENT |
DATE POST |
|
|
";
//loop through the query and print the result
while($info = mysqli_fetch_array($result)){
$data_id = $info['id'];
$data_name = $info['name'];
$data_email = $info['email'];
$data_comment = $info['comment'];
$data_date = $info['date_submit'];
print "
$data_name |
$data_email |
$data_comment |
$data_date |
Edit |
Delete |
";
}
print "";
?>
Some explanations
New column with the link delete link was introduced:
Delete |
I gets the record id stores into variable
$data_id and assigned it to the variable of our URL string
delete_id and this URL submits back to same page (hence no file name in the URL, unlike the edit)
?delete_id=$data_id
The second part of the URL
onclick=\"return confirm('Are you sure you want to delete?')\ is a JavaScript onclick event that will prompt user to confirm if the really want to delete the record, to prevent record from being deleted by mistake.
If a user confirm that they really want to delete the record then this section of our code that actually delete the record using the selected id is then executed
if(isset($_REQUEST['delete_id'])){
$delete_id = mysqli_escape_string($conn, $_REQUEST['delete_id']);
$query = "DELETE FROM feedback WHERE id = '$delete_id'";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if($result){
print "Record deleted";
}
}
Gitup link:
https://github.com/BenOnuorah/tea_learn_php_sample.git
Prompt before deleting
Record deleted
By:
Benjamin Onuorah
Login to comment or ask question on this topic
Previous Topic Next Topic