<?php
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();
$f($this);
$this->dbConn->commit();
} catch (\Throwable $e) {
$this->dbConn->rollBack();
throw $e;
}
}
public function multiInsert($queries)
{
$this->transaction( function () use ($queries) {
foreach ($queries as $row)
{
$this->query($row['query'], $row['params']);
}
});
}
public function updateRow($queries)
{
$this->transaction( function () use ($queries) {
$this->query($queries['query'], $queries['params']);
});
}
}
$myQuery = new MyQuery($pdo);
$insert_query[] = [
"query" => "INSERT INTO mytable (name, text) VALUES (:name, :text);",
"params" => [":name" => "Another Name", ":text" => "Another Text"],
];
$insert_query[] = [
"query" => "INSERT INTO mytable (name, text) VALUES (:name, :text);",
"params" => [":name" => "Another Name", ":text" => "Another Text"],
];
$myQuery->multiInsert($insert_query);
$update_query = [
"query" => "UPDATE mytable SET name=:name, text=:text WHERE id=:id",
"params" => [":name" => "Another Name (Updated)", ":text" => "Another Text (Updated)", ":id" => "1"],
];
$myQuery->updateRow($update_query);
PHP version :
PHP 7.4
PHP 8.0
PHP 8.1
PHP 8.2
PHP 8.3
PHP 8.4
Run PHP Code
Save snippet