スキップしてメイン コンテンツに移動

投稿

ラベル(SQL)が付いた投稿を表示しています

PHP: Execute Any DB Access Code in Transaction

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