0

I'm trying to delete from multiple tables at once using the JOIN but if for any reason the contacts table does not have any data for the user (applebottomjeans) the code below doesn't run correctly. Nothing gets deleted/removed. I get no error.

How do would fix this to maybe ignore that and to just delete the accounts table data and the subscriptions table data? Am I missing something here?

$user = $_GET['user_name'); // Username: applebottomjeans
  
// Delete user from records in accounts table, subscriptions table and contacts table
$sql = "DELETE FROM accounts, subscriptions, contacts 
USING accounts JOIN subscriptions JOIN contacts 
WHERE accounts.username = '$user' AND subscriptions.user_id = '$user' 
AND contacts.username = '$user' ";

if ($conn->query($sql) === TRUE) {
   echo "The users data was removed from our end.";
} else {
  echo "Error deleting user from our records. " . $conn->error;
}
code
  • 1,041
  • 1
  • 12
  • 28
  • 1
    JOIN gives rows only in the cases where data is present in all tables I would suggest using OUTER JOIN in your case – Girish Srivatsa Feb 03 '21 at 05:15
  • From what I read - this is what I ended up doing but i'm getting an "ERROR: Unknown table 'accounts' in MULTI DELETE https://codeshare.io/anbj3j – code Feb 03 '21 at 06:57
  • Can you change the tables if so set ON DELETE CASCADE then if source deleted all that is linked to it will also automatically get deleted – Girish Srivatsa Feb 03 '21 at 07:01
  • I cannot change the tables. Hmm... – code Feb 03 '21 at 07:24
  • You can look at [this](https://stackoverflow.com/questions/13951410/how-to-delete-without-on-delete-cascade-conflict-reference-constraint) maybe – Girish Srivatsa Feb 03 '21 at 07:43
  • @GirishSrivatsa thank you for helping me out. I will take a look but I think what you mention about foreign keys is the way to go. – code Feb 03 '21 at 23:30

0 Answers0