Skip to content

Instantly share code, notes, and snippets.

@kublaios
Created July 12, 2014 07:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kublaios/0bb208f4a69c5533d4d9 to your computer and use it in GitHub Desktop.
Save kublaios/0bb208f4a69c5533d4d9 to your computer and use it in GitHub Desktop.
Sample record function for using PDO's rollback transaction funcs.
<?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