What happens if a PHP script starts a transaction and then is terminated (timeout, fatal error, etc)? Does it automatically roll back and forget the previous transaction when the script is called again?

If a PHP script starts a transaction and is terminated before committing or rolling back, the transaction will remain open in the database until it is explicitly committed or rolled back. To prevent this, you can use a try-catch block to ensure that the transaction is properly handled even in case of a timeout or fatal error.

try {
    $pdo->beginTransaction();
    
    // Your transactional code here
    
    $pdo->commit();
} catch (Exception $e) {
    $pdo->rollBack();
    // Handle the exception (log, display error message, etc)
}