我想在数据库中添加记录后通过邮件或其他方式通知用户,这是否可能?例如使用ON INSERT
触发器执行一些PHP代码?
您不能使用mysql事件执行PHP脚本。
您必须在PHP端执行此操作。
检查插入命令是否成功执行并发送邮件。
只需检查插入是否成功,然后向客户发送电子邮件。
在mysql查询中不能执行php代码,但你可以检查查询是否成功并发送邮件,mysql_query()
会返回一个布尔值(true
或 false
)。如果你正在使用php,那么让我们以正确的方式使用它吧 ;)
if(mysql_query('// your query here')){
//mail someone
}
通过安装MySQL sys_exec UDF,可以在MySQL触发器中执行外部程序。
然而,这样做似乎是一种额外的负担。为什么要让MySQL触发通知,当插入数据的是PHP,并且此时您已经知道输入了数据呢?
在数据库插入/修改/删除时生成通知(电子邮件等)的最快最简单的方法是从执行数据库更改的脚本中进行。
<?php
$res = mysql_query( 'INSERT INTO `table` ( `field1` ) VALUES ( "One" )' );
if( $res ){
# Send Notification
}
?>
<?php
# A file containing an integer which is the Highest ID in the table
$indexFile = 'lastIndexID.txt';
# Get that Highest ID from the file, if it exists
$lastIndex = 0;
if( file_exists( $indexFile )
$lastIndex = (int) file_get_contents( $indexFile );
# Check the Database
$res = mysql_query( 'SELECT `id` FROM `table` ORDER BY `id` DESC LIMIT 1' );
if( $res && mysql_num_rows( $res )==1 ){
$row = mysql_fetch_assoc( $res );
# Check if the ID has increased (ie new rows added)
if( $row['id']>$lastIndex ){
# Send Notification
# The number of New Rows will be the difference between $row['id'] and $lastIndex
# Update the Index File
file_put_contents( $indexFile , $row['id'] );
}
}else{
# An Error Occurred
}
?>