rondog Posted August 5, 2009 Share Posted August 5, 2009 I have a function to delete a user. I also want to delete all of the users information in other tables. The way I am doing it right now works fine, but I was wondering if I could condense it into 1 query? if ($_GET['action'] == 'delete') { $id = $_GET['id']; $deleteUser = mysql_query("DELETE FROM users WHERE id = '".$id."'") or die(mysql_error()); if ($deleteUser) { $deleteProgress = mysql_query("DELETE FROM progress WHERE userid = '".$id."'") or die(mysql_error()); if ($deleteProgress) { $status = "Successfully deleted the selected user."; } } else { $status = "Failed to delete the selected user!"; } } Quote Link to comment Share on other sites More sharing options...
taquitosensei Posted August 5, 2009 Share Posted August 5, 2009 look into ON DELETE CASCADE you'll have to change add a foreign key here's some more info http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 5, 2009 Share Posted August 5, 2009 Just as an aside, do you realize you have an unhandled error in that logic? If the first query succeeds and the second does not, there is no response given. If you decide that you will continue with the current process of deleting records from each table individually, I would suggest reversing the process. Delete the associated records and then the parent record. Otherwise, if there is a problem, you would have orphaned records. Example: if ($_GET['action'] == 'delete') { $id = mysql_real_escape_string($_GET['id']); $deleteProgress = mysql_query("DELETE FROM progress WHERE userid = '".$id."'") or die(mysql_error()); if ($deleteProgress) { $deleteUser = mysql_query("DELETE FROM users WHERE id = '".$id."'") or die(mysql_error()); } if ($deleteProgress && $deleteUser) { $status = "Successfully deleted the selected user."; } else { $status = "Failed to delete the selected user!"; } } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.