Created
July 12, 2014 07:29
-
-
Save kublaios/0bb208f4a69c5533d4d9 to your computer and use it in GitHub Desktop.
Sample record function for using PDO's rollback transaction funcs.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Sample record function for using PDO's rollback transaction funcs.<br /> | |
* <b>By: </b>Kubilay Erdogan | |
* @param array $objects Object objects array (each object must be created) | |
* @return array Result array | |
*/ | |
public function recordObjects($objects = array()) { | |
if (count($objects) == 0) { $objects = $this->objects; } // set fields to self property if empty | |
if (count($objects) == 0) return true; // if still empty, then return. | |
// Begin transaction to rollback in case | |
$this->db->beginTransaction(); | |
$insertValues = array(); | |
foreach ($objects as $object) { | |
$objectArray = array( | |
"object_name" => $object->getName(), "object_created_at" => $object->getCreatedAt()); | |
$object_marks[] = '(' . placeholders('?', count($objectArray)) . ')'; | |
$insertValues = array_merge($insertValues, array_values($objectArray)); | |
} | |
$sql = "INSERT INTO `object` " . | |
"(`object_name`, `object_created_at`) " . | |
"VALUES " . implode(',', $object_marks); | |
$stmt = $this->db->prepare($sql); | |
$retArr = array(false); | |
try { | |
if ($stmt->execute($insertValues)) { | |
$retArr = result($this->db->commit()); // return transaction result since the result is true (true && $this->db->commit()) | |
} else { | |
$this->db->rollBack(); | |
$this->db->commit(); // finalize transaction | |
$retArr = result(false, $this->db->errorInfo()); | |
} | |
} catch (PDOException $e) { | |
$this->db->rollBack(); | |
$this->db->commit(); // finalize transaction | |
$retArr = result(false, $e->getMessage()); | |
} | |
return $retArr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment