How to delete from multiple tables

I'm trying to delete from multiple tables first from the main table where the id is created and then from the rest of the tables with the `unitid` is equal to the main `id`This is what I have but nothing is getting deleted. Please help:

$result = $mysqli->query("UPDATE login_users SET listing_count = '". $listingcount ."' WHERE email='".$delemail."' ");

$result = $mysqli->query("DELETE FROM units WHERE id={$id};"); 

$result = $mysqli->query("DELETE FROM amenities, bathrooms, bedrooms, contact, fees, images, ipaddress, location WHERE unitid={$id};"); 

Open in new window

Genesis5150Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

hieloCommented:
Try using INNER JOINS

DELETE T1, T2
FROM T1
INNER JOIN T2 ON T1.key = T2.key
WHERE condition

-- http://www.mysqltutorial.org/mysql-delete-join/
Julian HansenCommented:
The correct way of doing this is to create a relationship between units and amenities on units.id => amenities.unitid

Set this up as a cascade delete.

That way when you delete from the parent (units) table the child (amenities) records are automatically deleted as well.

The way you are doing it is problematic - apart from requiring more code to do the delete there is also potential for your database to get out of synch. Unless you wrap your delete's in a transaction if you delete from the first table and your script stops for whatever reason (network error / power outage etc) the amenities delete does not fire and you end up with orphan records.

Setup your relationships with cascade delete and when you delete from units the corresponding amenities records are automatically deleted.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.