1

I made some functions in PHP which perform some or the other database operation like insertion, deletion, updating, etc. and I call the functions every time I want to do some operation.

Now, lets say, I have the need to do the following:

  • Call function 1 which does a Database operation, wait for the return message then
  • Call function 2 which does another Database operation, wait for the return message then
  • Call function 3 which does some other Database operation, wait for the return message

If DB operation executed successfully in function1 and function2 but not in function3, then the complete operation is a failure since all three functions must be successful. In this case I would like to rollback the changes made by function1 and function2 since the operation is unsuccessful.

I thought of stacking the queries and executing them all together at once but the problem is I don't know when I have to execute the query stack.

eg.

if I call $obj->deletethread();
it calls $obj->deletemsg(); and $obj->deleteattachments(); and $obj->deletetags(); gets called

but this may not be the case all the time i.e.

if I call $obj->deletemsg();
$obj->deleteattachments(); and $obj->deletetags(); gets called

What I am trying to say is these functions can be called in any order by any other function. Is there any way to achieve this?

Why I need this: if a database operation is unsuccessful at any point, partial data is inserted in the tables where database operation was successful which I do not want since it will cause improper records.

halfer
  • 19,824
  • 17
  • 99
  • 186
Vignesh T.V.
  • 1,790
  • 3
  • 27
  • 48
  • 6
    Trannnnnnnnnnnnnnnsactions :) http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-transactions.html – Hanky Panky Apr 23 '13 at 04:32
  • 1
    You should probably be using transactions. See this question: http://stackoverflow.com/questions/2708237/php-mysql-transactions-examples – Steven Liao Apr 23 '13 at 04:32
  • @StevenLiao: What is the type of $db in http://stackoverflow.com/a/2708247/988268 – Vignesh T.V. Apr 23 '13 at 04:36
  • @vignesh, according to that post that is `semi-pseudo-code`. You could use any proper PHP code for MySQL, provided your database engine supports Transactions. – Hanky Panky Apr 23 '13 at 04:40
  • 1
    @vignesh: from the look of it, I guess PDO. PDO support MySQL transaction: http://php.net/manual/en/pdo.begintransaction.php – ariefbayu Apr 23 '13 at 04:40
  • Just so you know, you'll need the `InnoDB` engine type in MySQL for this - the default table type does not support transactions. – halfer Apr 23 '13 at 08:35
  • 1
    @halfer [The default engine was changed from MYISAM to INNODB in MySQL server 5.5](http://dev.mysql.com/doc/refman/5.5/en/innodb-default-se.html) – Jocelyn Apr 23 '13 at 14:33

0 Answers0