开发者

Possible to execute PHP on MySQL insert?

开发者 https://www.devze.com 2023-02-28 01:17 出处:网络
I actually want to mail or somehow notify a user when a record h开发者_JAVA百科as been added to the database. Is it possble? Like ON INSERT trigger, I execute some PHP?You can not execute PHP script w

I actually want to mail or somehow notify a user when a record h开发者_JAVA百科as been added to the database. Is it possble? Like ON INSERT trigger, I execute some PHP?


You can not execute PHP script with mysql events.

You have to do this in PHP end.

Check if the insert command is executed successfully and send mail.


Just check if the insert is succesfull and then send mail to the customer.


you cant execute php in a mysql query but you can check if the query was made successfully and then mail someone, mysql_query() will return a boolean (true or false). if you are using php, let's use it the right way ;)

if(mysql_query('// your query here')){
   //mail someone
}


It is possible to execute external programs from within MySQL triggers by installing MySQL sys_exec UDF

However, it seems that it's an overhead to do so. Why would you make MySQL trigger the notification when it's PHP that does the insert and at that point you know you entered the data?


The quickest and easiest way of generating notifications (emails, etc.) on database insertions/modifications/deletions is by doing so from the script which is performing the change in the database.

<?php
$res = mysql_query( 'INSERT INTO `table` ( `field1` ) VALUES ( "One" )' );
if( $res ){
 # Send Notification
}
?>

Failing that, in the event that you are not performing the database manipulations yourself (for some reason), or you want to be able to perform timed summaries (hourly, daily, weekly), you would need to use something like a Cron Job to poll the database and check for changes.

<?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
}
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号