I’m developing a shopping cart that persists for users (even if they are not logged in) via cookie or PHP session. So I’m creating a new record in users table whenever a not logged in user acesses the site, new carts and carts_items records when that user adds an item to the cart, and so on.
Many of these users will never return, cookies will expire and life goes on, but these tables will be populated with useless records.
The question is: how to get rid of these expired-cookie data?
Sounds like you are reinventing the PHP Session. I suggest just keeping the cart items out of the database and in a session array instead. You can configure the session to last as long as you want.
There are drawbacks to keeping cart items for long periods of time – products change/get removed etc etc and you will need to build in a regular check somewhere that all of cart items are still valid.
If you must store cart items in the database, then you’ll need to update the user record on every page view, with a timestamp. Using that you can have a cron job/scheduled task that deletes users and associated cart items that have a timestamp that is X days old.
Cron is a feature of Linux/Unix, it allows you to schedule tasks on a set point in time. For example, if you wanted to call your cleanup script everyday at 2am then your cronjob could look like:
From Wikipedia:
More info