I'm developing an application in CakePHP 2.4.7
I have my MySQL database and I've come to the necessity of triggering an update when the system's date and hour matches a due date I have in a table.
The table I'm using is the following
CREATE TABLE applied_surveys (id CHAR(36) NOT NULL PRIMARY KEY,
display_name VARCHAR(200),
area_id CHAR(36) NOT NULL,
survey_id CHAR(36) NOT NULL,
system_user_id CHAR(36) NOT NULL,
code VARCHAR(50),
init_date DATE,
due_date DATE,
init_hour TIME,
due_hour TIME,
completed INT,
state TINYINT DEFAULT 1,
max_responders INT,
created DATE, modified DATE,
FOREIGN KEY (area_id) REFERENCES areas(id),
FOREIGN KEY (survey_id) REFERENCES surveys(id),
FOREIGN KEY (system_user_id) REFERENCES system_users(id));
As you can see, I'm using an init date/hour and a due date/hour. My intention here is that I add a survey and I set a due date. When the due date and hour are reached the system must change my status(state) value to 0, meaning that the survey has been closed.
I'm integrating this database to a CakePHP application, but I'm not really sure where I should program the logic for this situation.
You can't write "sistem", it's system.
You will need to run a cron job every second/minute/hour, or whatever you prefer, that would check each record and see which ones are later than the system date. You can't expect it to run exactly at the time the dates become exactly the same, especially if you account for the seconds.
You can read about CRON jobs here : http://code.tutsplus.com/tutorials/managing-cron-jobs-with-php--net-19428
You don't necessarily need to update the column, you can simply return the comparison of the current system date and time with the due_date and due_time when the table is queried.
The separation of due_date and due_hour into two separate columns seems a bit odd, if we assume that neither of those will be null, we can convert those into a DATETIME, and then compare to NOW()
e.g.
SELECT NOW() <= CONCAT(s.due_date,' ',s.due_hour) AS `state`
FROM applied_surveys s
A MySQL row trigger gets fired when a row is modified. MySQL triggers don't get fired when the system clock advances.
You could run an UPDATE statement that identifies rows to be updated whenever you wanted, e.g.
UPDATE applied_surveys s
SET s.state = 0
WHERE NOW() >= CONCAT(s.due_date,' ',s.due_hour)
AND NOT (s.state <=> 0)
You can use events rather than triggers.
A stored procedure is only executed when it is invoked directly; a trigger is executed when an event associated with a table such as an insert, update or delete event occurs while an event can be executed at once or more regular intervals.
To set up events SET GLOBAL event_scheduler = ON;
CREATE EVENT IF NOT EXISTS update_state
ON SCHEDULE EVERY 1 day
DO
Update applied_surveys
Set state= 0
where due_date < curdate();
//similar condition can be added for hour.
To see all events in the schema
SHOW EVENTS;