PHP set_time_limit然后重置数据库更改

I have an API which is used by a mobile app to create user profiles. It seems that occasionally the app is timing out and displays an error message but the server continues to create the profile. The result is that we have a few duplicate profiles.

I'm thinking that, as a 'quick fix' that doesn't require a complete re-architecture I could try setting the execution time of the PHP script to match the timeout limit in the app. My question is, if this time limit is reached, can I somehow execute an 'undo changes to the database' script, either automatic, or one I specify?

I know I should really be looking more into why the PHP is reaching timeout limit at all (it's a couple of minutes!), but I have already tweaked bits on the server, and mostly the execution time is just a few milliseconds. There are only a few cases of the timeout occurring. For the one example I'm looking at the minute the user is based in Israel. Is the network connectivity bad in Israel? Can anyone think of anything that could cause the behaviour I'm experiencing?

One approach would be to use database transactions. I have experience in this with PostgreSQL, but I am sure MySql will do that too. You would wrap everything in a transaction. Then you can cancel the transaction when you detect failure, rolling back everything which belongs to the transaction.

Then, you can't catch a script timeout as it is a fatal error, however a transaction should be automatically rolled back (canceled) if it does not get committed, so you should be set...

Maybe it could work for you?

References:

Assumption: You're using MySQL w/ INNODB.

You should look into using transactions. With INNODB, the transaction will rollback if the session times out IF you set autocommit to 0 like so:

SET GLOBAL init_connect='SET autocommit=0';

Example of transactions with PDO:

try {
    // First of all, let's begin a transaction
    $db->beginTransaction();

    // A set of queries ; of one fails, an exception should be thrown
    $db->query('first query');
    $db->query('second query');
    $db->query('third query');

    // If we arrive here, it means that no exception was thrown
    // i.e. no query has failed ; and we can commit the transaction
    $db->commit();

} catch (Exception $e) {
    // An exception has been thrown
    // We must rollback the transaction
    $db->rollback();
}