class MyQuery
{
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();
return $f($this);
$this->dbConn->commit();
} catch (\Throwable $e) {
$this->dbConn->rollBack();
throw $e;
}
}
}
and then using this generic transaction()
method we can create a helper function for the specific multiple insertqueries case
public function multiInsertmultiQueryTransavtion($queries)
{
$this->transaction( function () use ($queries) {
foreach ($queries as $row)
{
$this->query($row['query'], $row['params']);
}
});
}
$insert_query[] = [
"query" => "INSERT INTO mytable (name, text) VALUES (:name, :text);",
"params" => [":name" => "Name Test", ":text" => "Text Test"],
];
$insert_query[] = [
"query" => "INSERT INTO mytable (name, text) VALUES (:name, :text);",
"params" => [":name" => "Another Name", ":text" => "Another Text"],
];
$pdo = new PDO ...;
$myQuery = new MyQuery($pdo);
$myQuery->multiInsert>multiQueryTransaction($insert_query);