so Im trying to wrap SQL INSERT statements to PDO transaction in PHP OOP. I don't know if I'm doing it right and this is the best/easiest way to do it.
So what is important for me is:
There can be multiple(unpredictable) INSERT statement (which will be in loop in the final code) I want to wrap all of these queries to transaction and commit(execute) only at the end of the code (after loop in final code) And of course in PHP OOP.
My code looks like this right now:
class.inc.php
class MyQuery {
protected $DB_CONN;
private $DB_insert_query;
public function __construct($DB_CONN) {
$this->PDO_CONN = $DB_CONN->DB_CONN();
}
public function insert_query($insert_query) {
$this->DB_insert_query = $insert_query;
}
public function commit() {
try {
$this->PDO_CONN->beginTransaction();
foreach ($this->DB_insert_query as $query) {
$stmt = $this->PDO_CONN->prepare($query["query"]);
$stmt->execute($query["params"]);
}
$this->PDO_CONN->commit();
}
catch (PDOException $e) {
$this->PDO_CONN->rollBack();
error_log("Error occurred. Error message: " . $e->getMessage() . ". File: " . $e->getFile() . ". Line: " . $e->getLine(), 0);
}
if ($stmt->rowCount()) {
return true;
} else {
return false;
}
}
}
insert.php
$DB_CONN = new DataBase;
$myQuery = new MyQuery($DB_CONN);
$insert_query[] = array("query" => "INSERT INTO mytable (name, text) VALUES (:name, :text);",
"params" => array(":name" => "Name Test", ":text" => "Text Test")
);
$myQuery->insert_query($insert_query);
$insert_query[] = array("query" => "INSERT INTO mytable (name, text) VALUES (:name, :text);",
"params" => array(":name" => "Another Name", ":text" => "Another Text")
);
$myQuery->insert_query($insert_query);
print_r($myQuery->commit());
Thank you for your help!