I am going to implement transactions in my php scripts and I am doing some tests to help myself understand how they work. I have the following code snippet:
try{
$db->beginTransaction();
$update = "UPDATE persons SET first_name = 'Adam' WHERE person_id = 4";
$stmt = $db->exec($update);
$select = "SELECT person_id, column_that_doesnt_exist FROM persons";
try{
$stmt = $db->prepare($select);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode('success');
} catch (PDOException $e) {
echo 'execute failure';
}
echo ' code gets here';
$db->commit();
} catch(PDOException $e){
$db->rollBack();
echo json_encode('commit failure');
}
which outputs:
execute failure code gets here
And the name of man 4 is updated to Adam.
Now I am sure that this is happening because the second request was never executed, because it was never executed, as it preparewas a point of failure.
It would be nice if it PDOExceptionwere thrown out for the latter catch, since it was added to the inside try, but I can get around this.
Now, if I pulled out "internal" tryand got this code:
try{
$db->beginTransaction();
$update = "UPDATE persons SET first_name = 'Adam' WHERE person_id = 4";
$stmt = $db->exec($update);
$select = "SELECT person_id, column_that_doesnt_exist FROM persons";
$stmt = $db->prepare($select);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$db->commit();
} catch(PDOException $e){
$db->rollBack();
echo json_encode('commit failure');
}
commit fails, db rolls back and displays commit failureas expected.
, try-catch try (), commit ? .... , ....