2016-04-04 7 views
0

私は1つのテーブルに挿入し、別のテーブルを更新する必要があり、それら2つのものが絶対に一緒に起こる必要があるとしましょう。例コード:2つのクエリが互いに依存し、2つ目のクエリが失敗した場合のエラーの処理?

$insert = query('INSERT INTO first_table'); 

if ($insert->successful) { 
    $update = query('UPDATE second_table'); 

    if ($update->successful) { 

    } else { 
     log($update->errorMessage); 
     // magically revert the effects from the first query? 
     // store the query and try to execute it on the next request? 
    } 
} 

明らかに私はエラーをログに記録しますが、すべてのデータが同期外れ/破損しています。この場合、私は何をすべきですか?あるいは、私は全体のことを間違ってやっているのですか?それは2つの質問ではありませんか?

+2

、トランザクションを必要とします'transactions'を使う必要があります。もしうまくいくなら' commit' else 'rollback' –

+2

http://dev.mysql.com/doc/refman/5.7/en/commit.htmlを見てください。あなたのPHPスクリプトとmysqlサーバーを接続するために使用するここでは、そのための "特殊な"機能/方法があります。 http://docs.php.net/manual/en/mysqli.begin-transaction.php – VolkerK

+0

TRANSACTIONS(http://dev.mysql.com/doc/refman/5.7/en/commit.html)はあなたの友人です。 .. – MarcoS

答えて

2

あなたはさらに、開始トランザクションの状態を検証し、

//Start your transaction 
$start = query('START TRANSACTION'); 
$insert = query('INSERT INTO first_table'); 

if ($insert->successful) { 
    $update = query('UPDATE second_table'); 

    if ($update->successful) { 
     //Do the changes 
     $state = query('COMMIT'); 
    } else { 
     //Undo changes 
     $state = query('ROLLBACK'); 
     log($update->errorMessage); 
     // magically revert the effects from the first query? 
     // store the query and try to execute it on the next request? 
    } 
} else { 
    //Undo changes 
    $state = query('ROLLBACK'); 
} 
関連する問題