Reusable Code for Execute Any DB Access Code in Transaction In this post, I will show you highly reusable utility code for wrapping and executing original db access code in transaction. Anyway let's show you the code. function executeInTransaction(callable $func) { $conn = new PDO(SERVER_NAME, USERNAME, PASSWORD, DBNAME); try { $conn->beginTransaction(); $func($conn); $conn->commit(); } catch (Exception $ex) { $conn->rollBack(); throw $ex; } } Oh, how to use? You just simply passing your core DB access code as the callable $func argument. Okay, let me show you example in next section. Example Usage First, assume you have following 2 methods for inserting data to DB. CONST SERVER_NAME = 'localhost'; CONST USERNAME = "username"; CONST PASSWORD = "password"; CONS...
IT関連の技術やプログラミングを中心に記事を書いています。ハードウェアも好きなので、日々のちょっとしたお役立ち情報も投稿しています。