Paolo Uriel N. Enriquez Paolo Uriel N. Enriquez - 1 month ago 8
PHP Question

Automatically change database row item if it has not been changed within a certain time

I'm having a hard time on creating a time allowance for reservations in PHP. I did research regarding this but unfortunately I do not know what are the exact terms for this.

I already have a working reservation module, I need to add a feature that automatically cancels that reservation within 30 minutes if it is not confirmed by the client.

Is there a PHP code fragment where it will automatically set the value of a row if it has not been changed within 30 mins?

PS: Sorry for bad english.

Answer Source

Is there a PHP code fragment where it will automatically set the value of a row if it has not been changed within 30 mins?

No. This is data-centric, presumably your "reservation" is stored in a database (e.g. MySQL)?

PHP as a platform is in 99.9% of scenarios responding to a request (either CLI or HTTP) - or so called "event driven". There is no easy way to create an "event" for something expiring in the future without moving your mind beyond pure PHP.

You can be event driven in your updating of an "updated at" field by using your DBMS' timestamp (e.g. see ON UPDATE CURRENT_TIMESTAMP()) from which you can check (on any future event) whether the record has "expired" (last updated timestamp + 30 minutes).

If you need to generate an event when expiry occurs (e.g. send an email to say the reservation was cancelled), unless you have some sort of 'deferred execution' (a feature of some queuing platforms - outside the scope of this answer) you will need to periodically poll (the "kind-of" opposite to event driven) to find any records which have expired.

The most common means of doing that through PHP on a LAMP stack is by writing a cronjob. That's a forever-running service which will (with a maximum frequency of every 60 seconds) trigger your code.

If you're heading down the polling route but only need to manipulate date (no email sending etc), you could investigate using your DBMS scheduler (e.g. MySQL events). A word of warning though - hiding business logic inside the database doesn't always lead to maintainable solutions.


Added note: If you're not already using a PHP framework, consider discovering the joys of products like laravel which give you task scheduling out of the box.