问题
What I want to do is to monitor a table in mysql which is always auto-updated by a sms gateway.
The script should be monitored continuously and as soon as there is a new entry in the table, a php script ritn to perform further operations should be triggered.
How do I achieve this?
回答1:
I've done exactly this lots of times using cron. So your php script starts by seeing if there is a new entry, and then does what it needs to do if there is. If there's nothing to work on, it just exits immediately. One thing to bear in mind is that if the script takes a long time to run, you want to make sure your cron jobs are set accordingly, so they don't overlap.
One simple way to achieve this is to have a special column in the table which indicates whether the row has been examined by the php script or not. So when the php script runs, it looks for all data that has that field false. Something like this:
SELECT id from my_table where dealt_with = FALSE;
And then when it's run on those rows, it updates them:
UPDATE my_table set dealt_with = TRUE where id=1234;
回答2:
I suggest adding an AFTER UPDATE trigger to your table.
Each time a record is updated, your trigger code will be automatically executed.
The code in the trigger is a list of MySQL statements.
回答3:
Jocelyn suggested a pretty good solution for a project with documentation, otherwise it is a killer for other developers that might want to change anything as it is something that is always overlooked.
The limitation with MySQL AFTER UPDATE
is that it can only run SQL, not a PHP script. So the best solution would be to run a CRON job every * minutes that launches a PHP script, which checks for the last value of the auto-increment field such as an id
field, for example with mysql_insert_id. The reason behind using this logic is because you would not want to check for the number of rows as some of them might have been deleted.
来源:https://stackoverflow.com/questions/11232915/how-to-continuously-monitor-a-table-in-a-mysql-database-and-triger-a-php-script