How to execute additional SQL in After Execute family events in CCS
Hi! This article is about how to execute some addtitional SQL after the primary SQL in the CodeCharge Studio’s Record has been executed.
Very often I have to perform some additional manipulations with the database after the Record submission. In this article I want to share the approach I use to reach the desired result. If you use a different approach to reach the same result I’m waiting your comments!
So, here’re some steps:
1. You should have already a Record that performs Insert, Update or Delete.
2. Choose the event you will work with. It may be After Execute Insert, After Execute Update or After Execute Delete. I’ve chosen After Execute Insert to test with it in this example.
3. Add the Custom Code to the After Execute Insert event of the Record.
4. Try this code:
/* $master is a Record we work with. * In the next line condition we check that no errors have been occured. */ if($master->ds->Errors->Count() == 0 && $master->ds->CmdExecution) { // In the code below, we get the ID that has been inserted last time. $db = new clsDBTest(); $db->SQL = 'SELECT LAST_INSERT_ID() AS master_id'; $db->query($db->SQL); $result = $db->next_record(); if ($result) { $master_id = $db->f("master_id"); } else { $master_id = -1; } $db->close(); /* In this code snippet, we insert a new record to * another "details" table with the "master id" value. */ if ($master_id != -1) { $db = new clsDBTest(); $db->SQL = "INSERT INTO details (`master`, `test_field`) "; $db->SQL += "VALUES ($master_id, 'test')"; $db->query($db->SQL); $db->close(); } } |
By the way, in this example I use PHP and MySQL. If you have an another configuration I think you can simply adapt this example to your configuration.
Great tutorial, thanks for sharing!
What happens if two users execute the form simultaneously?
Hi, Eydun!
Yes, you are right. Here’s a little bug! Instead of using a new connection to MySql you should use an existing connection. In this context, you should use $master->DataSource->query(“some sql”). Using the Record’s connection is safe because LAST_INSERT_ID() works on a per-connection basis.
http://dev.mysql.com/doc/refman/5.1/en/information-functions.html#function_last-insert-id
I’ll modify this example as soon as possible. Thanks for comment!