Overview
PDO connection options and transaction wrapper for MySQL applications.
Code example
<?php
declare(strict_types=1);
function createPdo(string $dsn,string $user,string $password): PDO {
return new PDO($dsn,$user,$password,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,PDO::ATTR_EMULATE_PREPARES=>false]);
}
function inTransaction(PDO $pdo,callable $work): mixed {
$pdo->beginTransaction(); try{$result=$work($pdo);$pdo->commit();return $result;}
catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();throw $e;}
}
How to use it
Place the snippet in a namespaced helper or service file, adapt its inputs to your application and add tests for expected and edge-case behavior.
Notes
The example is intentionally small. Validate untrusted input, handle exceptions and document any PHP extension or database requirements.