Hi I was wondering if there was a way in MySQL to automatically send an e-mail to myself whenever there is a row added to a MySQL table?
The best way to achieve this would be using a trigger and a cron. Create a 'notification queue' table and populate that with a trigger when a row is inserted in the desired table.
eg.
CREATE TABLE `notification_queue` (
`notification_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`sent` tinyint(1) unsigned NOT NULL,
PRIMARY KEY (`notification_id`)
);
Then define a simple trigger:
DELIMITER $$
CREATE TRIGGER t_notification_insert
AFTER INSERT ON [table_being_inserted]
FOR EACH ROW
BEGIN
INSERT INTO `notification_queue` (`sent`) VALUES (0);
END$$
DELIMITER ;
From that point, all you need to do is make a crontab run on the server (say every minute) which selects from the notification
table where sent = 0
, send the notification and set sent = 1
As far as I know, that's the best way to get that information out of the DB without reading the bin logs.
If you need an example of the script to run with cron:
#!/bin/bash
DB_USER=''
DB_PASS=''
DB_NAME=''
ID=`mysql -u$DB_USER -p$DB_PASS $DB_NAME -Bse "SELECT notification_id FROM notification_queue WHERE sent=0 LIMIT 1;"`
if [[ ! -z $ID ]]
then
# SEND MAIL HERE
RESULT=`mysql -u$DB_USER -p$DB_PASS $DB_NAME -Bse "UPDATE notification_queue SET sent=1 WHERE notification_id = $ID;"`
echo "Sent"
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With