PHPize Online / SQLize Online

A A A
Share      Blog   Popular
Copy Format Clear
Copy
Copy Format Clear
<?php $pdo->query("create table t1 (i int)"); $pdo->query("create table t2 (i int)"); $db = new Database($pdo); $inserts = [ ["query" => "insert into t1 (i) values (?)","params" => [1]], ["query" => "insert into t2 (i) values (?)","params" => [1]], ]; $db->multiQueryTransaction($inserts); echo json_encode($pdo->query("select * from t1")->fetchAll()), "\n"; echo json_encode($pdo->query("select * from t2")->fetchAll()), "\n"; $db->transaction( function () { $this->query("insert into t1 (i) values (?)",[2]); $this->query("insert into t2 (i) values (?)",[2]); }); echo json_encode($pdo->query("select * from t1")->fetchAll()), "\n"; echo json_encode($pdo->query("select * from t2")->fetchAll()), "\n"; class Database { public $dbConn; public function __construct($dbConn) { $this->dbConn = $dbConn; } public function query($query, $params) { $stmt = $this->dbConn->prepare($query); $stmt->execute($params); return $stmt; } public function transaction(Callable $f) { try { $this->dbConn->beginTransaction(); $ret = $f($this); $this->dbConn->commit(); return $ret; } catch (\Throwable $e) { $this->dbConn->rollBack(); throw $e; } } public function multiQueryTransaction($queries) { $this->transaction( function () use ($queries) { foreach ($queries as $row) { $this->query($row['query'], $row['params']); } }); } }
Show:  
Copy