0

I am having two table consider table1 and table2. I need to do a trigger after inserting into table1.

Trigger has to do some thing like retrieving data from two other tables using select query (it retrieves more than one row) do some calculations with the data retrieved and then it need to insert it into table2 as single row.

I think it's not possible to do these with in a trigger, so I decided to call a php file from that trigger which does all those things. But some persons says calling php from a trigger is not practically good and it has some security risk.

halfer
  • 19,824
  • 17
  • 99
  • 186
user3496195
  • 139
  • 1
  • 2
  • 11
  • what's stopping you writing the php to do this ? –  Jun 26 '14 at 04:27
  • Dont write a trigger. Put the entire thing in php. insert-> check if successful -> do your thing – SNAG Jun 26 '14 at 05:15
  • @SNAG Thanks but please explain me that since i am a beginner in php – user3496195 Jun 26 '14 at 05:18
  • @SNAG also i need to do that even im not inserting using php.that is if i directly insert into db table or by importing Excel into a table – user3496195 Jun 26 '14 at 05:20
  • Hey in that case you have to call the php file from a trigger. there is no other way. but before that please make sure what you are doing in the php file cannot be done in the trigger itself. – SNAG Jun 26 '14 at 05:26

2 Answers2

0

A Simple Example will help you out.

$sql="INSERT INTO  `table1` (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";

$result = mysql_query($sql) ;

if($result)
{
// Record successfully inserted , place your code which needs to be executed after successful insertion
}

else
{
 // Insertion failed 
}

I assume you would be using mysqli and not mysql becuase mysql_query is deprecated as of PHP 5.5.0 but this is just an example to help you understand the logic.

Adeel Raza
  • 628
  • 5
  • 17
  • i need to do that even im not inserting using php.that is if i directly insert into db table or by importing Excel into a table – user3496195 Jun 26 '14 at 05:44
0

Ok got you .. In this case you need to create a TRIGGER something like this.

CREATE
    TRIGGER `event_name` BEFORE/AFTER INSERT/UPDATE/DELETE
    ON `database`.`table`
    FOR EACH ROW BEGIN
        -- trigger body
        -- this code is applied to every 
        -- inserted/updated/deleted row
    END;

This Question has already been answered check the link below.

MySQL trigger On Insert/Update events

Hope this helps.

Community
  • 1
  • 1
Adeel Raza
  • 628
  • 5
  • 17