Sorry if this is a duplicate question, but I’m trying to figure out how to create a delete query using PHP PDO and MySQL.
I have a table on a webpage that has an action column with two buttons. One for editing and one for deleting (like this):
The edit code redirects the user to another page to edit the user’s information. The edit code is functional, but the delete code doesn’t appear to work.
Here is what I have so far:
<?php
include ('../dbconnect.php');
$id = $_GET['id'];
$stmt = "DELETE FROM users WHERE id = :id";
$stmt->bindParam(':id', $id);
// Delete
if(isset($_POST['btn_delete'])) {
$id = $_GET['id'];
$stmt->execute();
header('Location: ../../users.php');
}
?>
My goal is to redirect the user back to the users.php
file where the table is. I have a confirmation as well using a Bootstrap Modal (code shown below) that shows when the user clicks the Delete Icon in the users table:
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Delete User</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Are you sure you want to delete this user?</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
<a class="btn btn-danger" href="api/users/delete.php">Delete</a>
</div>
</div>
</div>
</div>
I currently see these two errors when I run the script:
Notice: Undefined index: id in C:\xampp\htdocs\ccrp\api\users\delete.php on line 5
Fatal error: Uncaught Error: Call to a member function bindParam() on string in C:\xampp\htdocs\ccrp\api\users\delete.php:8 Stack trace: #0 {main} thrown in C:\xampp\htdocs\ccrp\api\users\delete.php on line 8
Am I doing this right? How do I fix it?