What should I do if anything related to database communication goes wrong?
<p>Here's the problem: When a script starts modifying the database and something goes wrong, the database is usually corrupted. For example, lets say we have a User table and a Photos table. </p>

<p>A script creates a user dataset and in the next lines it attempts to create a photo dataset. The photo has a user_id column. Now lets assume something goes wrong and PDO's lastInserId() doesn't return the id of the user. So what happens in worst case: We get a user with no photo, and a photo with no valid user_id. Broken reference. 3 weeks to debug.</p>

<p>Are there any good strategies to follow, to prevent exactly this kind of problems? In my code below, you can see that I at least try to log that to a file and quit the script execution to prevent more damage and db curruption.</p>

<pre><code>public function lastInsertId() {
    $id = $this-&gt;dbh-&gt;lastInsertId();
    if (!is_numeric($id)) {
        $this-&gt;logError("DB::lastInsertId() did not return an id as expected!");
        die();
    }
    return $id;
}
</code></pre>

<p>Maybe I have to use Transactions all over the place, at any time where an query B depends on a query A, and so forth? Is that the solution to go?</p>

<p>Should I do a "precaution rollback" before the die() call? I guess it would not hurt much at this point, would it? I'm not sure...</p>
