简体   繁体   中英

MySQL PDO delete users older than 2 days, delete content from other tables with user_id

I am making a small system to clean up the database. Every person that visits the site gets put in the db, but if he/she doesn't register, he/she should be removed from the database with a cronjob or so if the time when he/she first visited the site is longer than 2 days. The date is stored in MySQL as a timestamp but looks like this: 2013-06-05 01:18:43 .

So what I thought about doing was the following:

$STH = $DBH->query("DELETE FROM user WHERE type=0 AND joindate < ".date('d-m-Y H:i:s',time()-$userLife));

Like this, the format of the timestamp is the same as in MySQL. I'm using $userLife so I can easily adjust this var at the beginning of my script.

The problem is however, that I also need to do queries for other tables containing this user_id . For example the table pages :

id | user_id | level | time | views

In this table, it is possible that there are multiple instances of user_id .

Can this be done in one single query, or do I need to first loop through all the users, for each user then do the DELETE-queries for 3 other tables and after that loop delete all the user s?

Ideally, you'd define things with a FOREIGN KEY constraint, and define an ON DELETE CASCADE , which automagically will delete all that related data for you. If that's not possible for some reason (stuck with a MyISAM table for instance), you could simply JOIN the related tables (yes, you can delete from more then 1 table at once ). If it's your first time doing that, do it on a testdatabase, and certainly not in production.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM