I'm deleting data from the dB in multiple tables. I'm sending the data username over to delete-member.php
using a modal to confirm (delete) like this:
<script>
$('.delete-button').on('click', function (e) {
var username = $(this).attr('data-id');
$('.confirm-delete').attr('data-id',username);
});
$(".confirm-delete").on('click', function (e) {
var username = $(this).attr('data-id');
console.log(username);
//Ajax for deleting category
$.ajax({
url: 'handlers/delete_member.php',
type: 'GET',
data: {username: username},
error: function() {
alert('Something went wrong');
},
success: function(data) {
console.log("Member Deleted");
}
});
location.href="site_members.php?username="+username;
});
</script>
Everything works fine here, I $_GET
the username and delete the data. The challenge I'm having is if that particular user has been using the system for awhile. In order to do a hard delete of that user, I need to mk. sure that username
is deleted in multiple tables. 15 to be exact.
Using prepared statements, I set about deleting each occurrence as follows:
if(isset($_GET["username"])) {
$userFromURL = $_GET["username"];
//delete member information from users
global $con;
$delete_mbrQ = mysqli_prepare($con, "DELETE FROM users WHERE username=?");
$delete_mbrQ->bind_param("s", $userFromURL);
$delete_mbrQ->execute();
$delete_mbrQ->close();
//delete member posts
$delete_postsQ = mysqli_prepare($con, "DELETE FROM posts WHERE added_by=?");
$delete_postsQ->bind_param("s", $userFromURL);
$delete_postsQ->execute();
$delete_postsQ->close();
//delete messages
$del_msgsQ = mysqli_prepare($con, "DELETE FROM messages WHERE user_to=? OR user_from=?");
$del_msgsQ->bind_param("ss", $userFromURL, $userFromURL);
$del_msgsQ->execute();
$del_msgsQ->close();
etc...(I won't put all 15 but you get the gist) I did this for all 15 tables where username
occurs and it works fine. However, looking at this big page of recurring code, I'm wondering if there is a more efficient way to do this? Can I combine this into one or two statements to achieve the same thing?
I've been researching on this, but most of what I've read talks more about setting up a foreign key, which I've done in some cases but clearly not for this. I also don't find much for Prepared Statements and instances where the column names are different. Any help, examples, links etc. would be appreciated.