/** * @param \Closure $queries * @return bool */ public function transaction(\Closure $queries) { $this->connection->beginTransaction(); try { $queries($this); $this->connection->commit(); return true; } catch (Exception $e) { $this->connection->rollback(); return false; } }
/** * Executes a function in a transaction. * * @param callable $callable The function to execute transactionally * * @return mixed The non-empty value returned from the closure or true instead. * * @throws \Exception during execution of the function or transaction commit, * the transaction is rolled back and the exception re-thrown */ public function transactional(callable $callable) { $this->pdo->beginTransaction(); try { $return = call_user_func($callable, $this); $this->pdo->commit(); return $return ?: true; } catch (\Exception $exception) { $this->pdo->rollback(); throw $exception; } }
/** * Rollback a transaction. */ private function rollback() { if ($this->transaction) { $this->db->rollback(); $this->transaction = false; } }
/** * Rolls back a transaction and returns true if the rollback was successfull. * * @return boolean */ public function rollBackTransaction() { if ($this->activeTransactions === 0) { return false; } try { $this->activeTransactions--; if ($this->activeTransactions === 0) { if (WCF::benchmarkIsEnabled()) { Benchmark::getInstance()->start("ROLLBACK", Benchmark::TYPE_SQL_QUERY); } $result = $this->pdo->rollback(); } else { if (WCF::benchmarkIsEnabled()) { Benchmark::getInstance()->start("ROLLBACK TO SAVEPOINT level" . $this->activeTransactions, Benchmark::TYPE_SQL_QUERY); } $result = $this->pdo->exec("ROLLBACK TO SAVEPOINT level" . $this->activeTransactions) !== false; } if (WCF::benchmarkIsEnabled()) { Benchmark::getInstance()->stop(); } return $result; } catch (\PDOException $e) { throw new DatabaseException("Cannot rollback transaction: " . $e->getMessage(), $this); } }
public function createService(ServiceLocatorInterface $serviceLocator) { $config = $serviceLocator->get('config'); try { $pdo = $pdo = new \PDO($config['dbAdapterPostgre']['dsn'], $config['dbAdapterPostgre']['username'], $config['dbAdapterPostgre']['password']); $sql = " \n SELECT a.id as id\n FROM info_users a \n where \n a.username = :username "; $statement = $pdo->prepare($sql); //print_r('--user id-->'.$serviceLocator->get('identity')); $statement->bindValue(':username', $serviceLocator->get('identity'), \PDO::PARAM_STR); //echo debugPDO($sql, $parameters); $statement->execute(); $result = $statement->fetchAll(\PDO::FETCH_ASSOC); $userID = true; if (isset($result[0]['id'])) { $userID = (int) $result[0]['id']; } $errorInfo = $statement->errorInfo(); if ($errorInfo[0] != "00000" && $errorInfo[1] != NULL && $errorInfo[2] != NULL) { throw new \PDOException($errorInfo[0]); } //return array("found" => true, "errorInfo" => $errorInfo, "resultSet" => $result); return $userID; } catch (\PDOException $e) { $pdo->rollback(); return array("found" => false, "errorInfo" => $e->getMessage()); } }
/** * Rollsback a transaction * * @return bool true on success, false otherwise */ public function rollbackTransaction() { if (!$this->_connection->inTransaction()) { return false; } return $this->_connection->rollback(); }
public function createService(ServiceLocatorInterface $serviceLocator) { $config = $serviceLocator->get('config'); try { $pdo = $pdo = new \PDO($config['dbAdapterPostgre']['dsn'], $config['dbAdapterPostgre']['username'], $config['dbAdapterPostgre']['password']); $sql = " \n SELECT \n REPLACE(TRIM(SUBSTRING(crypt(sf_private_key_value,gen_salt('xdes')),6,20)),'/','*') AS public_key\n FROM info_users a \n INNER JOIN sys_acl_roles sar ON sar.id = a.role_id AND sar.active=0 AND sar.deleted=0 \n WHERE a.username = :username \n AND a.password = :password \n AND a.deleted = 0 \n AND a.active = 0 \n Limit 1 \n \n "; $statement = $pdo->prepare($sql); $statement->bindValue(':username', $_POST['eposta'], \PDO::PARAM_STR); $statement->bindValue(':password', md5($_POST['sifre']), \PDO::PARAM_STR); //echo debugPDO($sql, $parameters); $statement->execute(); $result = $statement->fetchAll(\PDO::FETCH_ASSOC); $publicKey = true; if (isset($result[0]['public_key'])) { $publicKey = $result[0]['public_key']; } $errorInfo = $statement->errorInfo(); if ($errorInfo[0] != "00000" && $errorInfo[1] != NULL && $errorInfo[2] != NULL) { throw new \PDOException($errorInfo[0]); } //return array("found" => true, "errorInfo" => $errorInfo, "resultSet" => $result); return $publicKey; } catch (\PDOException $e) { $pdo->rollback(); return array("found" => false, "errorInfo" => $e->getMessage()); } //return false; }
/** * 析构函数 */ public function __destruct() { if (!self::$autocommit) { $this->handler->rollback(); $this->handler->autocommit(true); } }
/** * Annule la transaction ou bien revient au point de sauvegarde courant * @return bool */ private function rollback() { if (--$this->transactionCounter) { $this->pdolink->exec('ROLLBACK TO SAVEPOINT trans'.($this->transactionCounter + 1)); return true; } return $this->pdolink->rollback(); }
public function rollback() { if (--$this->transactionCounter) { $this->exec('ROLLBACK TO trans' . $this->transactionCounter + 1); return true; } return parent::rollback(); }
public function rollback() { if (--$this->transactionCounter) { $this->exec('ROLLBACK TO ' . static::SAVEPOINT_PREFIX . $this->transactionCounter + 1); return true; } return parent::rollback(); }
function rollback() { if ($this->transactionCounter >= 0) { $this->transactionCounter = 0; return parent::rollback(); } $this->transactionCounter = 0; return false; }
/** * Rolls back a running transaction * * @access public * @return Database */ public function RollbackTransaction() : Database { /* ------------------------------------------------------------------------------------------------------ ACT ------------------------------------------------------------------------------------------------------ */ self::$PDO->rollback(); /* ------------------------------------------------------------------------------------------------------ RETURN ------------------------------------------------------------------------------------------------------ */ return $this; }
/** * Wrapper for PDO's rollback. * * This wrapper will use ROLLBACK TO SAVEPOINT when a nested transaction is * rolled back. * * This function will not attempt to auto-reconnect, because if the session * has timed out, so has any active transaction, and thus an exception shall be * raised. * * @see http://www.php.net/manual/en/pdo.rollback.php */ public function rollback() { if ($this->active_transactions == 0) { throw new \RuntimeException('Rollback failed, no active transaction.'); } $this->active_transactions -= 1; if ($this->active_transactions == 0) { return $this->pdo->rollback(); } else { $this->pdo->exec(sprintf('ROLLBACK TO SAVEPOINT T%d', $this->active_transactions)); return true; } }
/** * @see DataBackend::update() * @throws DataBackendException */ public function update() { $useTA = false; try { $fileUtil = new FileUtil(); $fileBackend = new FileDataBackend(tempnam($fileUtil->getTempDirectory(), 'bav')); //$fileBackend = new FileDataBackend('E:\xampp\htdocs\sepatool\external\bav\data\blz_2016_03_07_txt.txt'); $fileBackend->install(); $insertBank = $this->pdo->prepare("INSERT INTO {$this->prefix}bank\n (id, validator, mainAgency)\n VALUES(:bankID, :validator, :mainAgency)"); $insertAgency = $this->pdo->prepare("INSERT INTO {$this->prefix}agency\n (id, name, postcode, city, shortTerm, pan, bic, bank)\n VALUES (:id, :name, :postcode, :city, :shortTerm, :pan, :bic, :bank)"); try { $this->pdo->beginTransaction(); $useTA = true; } catch (\PDOException $e) { trigger_error("Your DBS doesn't support transactions. Your data may be corrupted."); } $this->pdo->exec("DELETE FROM {$this->prefix}agency"); $this->pdo->exec("DELETE FROM {$this->prefix}bank"); foreach ($fileBackend->getAllBanks() as $bank) { try { $insertBank->execute(array(":bankID" => $bank->getBankID(), ":validator" => $bank->getValidationType(), ":mainAgency" => $bank->getMainAgency()->getID())); $agencies = $bank->getAgencies(); $agencies[] = $bank->getMainAgency(); foreach ($agencies as $agency) { $insertAgency->execute(array(":id" => $agency->getID(), ":name" => $agency->getName(), ":postcode" => $agency->getPostcode(), ":city" => $agency->getCity(), ":shortTerm" => $agency->getShortTerm(), ":bank" => $bank->getBankID(), ":pan" => $agency->hasPAN() ? $agency->getPAN() : null, ":bic" => $agency->hasBIC() ? $agency->getBIC() : null)); } } catch (NoMainAgencyException $e) { trigger_error("Skipping bank {$e->getBank()->getBankID()} without any main agency."); } } // Update modification timestamp $modificationStmt = $this->pdo->prepare("UPDATE {$this->prefix}meta SET value=:value WHERE name=:name"); $modificationStmt->execute(array(":name" => MetaData::LASTMODIFIED, ":value" => time())); if ($useTA) { $this->pdo->commit(); $useTA = false; } //$fileBackend->uninstall(); } catch (Exception $e) { try { if ($useTA) { $this->pdo->rollback(); } throw $e; } catch (\PDOException $e2) { throw new DataBackendIOException(get_class($e) . ": {$e->getMessage()}\nadditionally: {$e2->getMessage()}"); } } }
/** * Rollback a transaction. * * If this this call to rollback corresponds to the outermost call to * beginTransaction(), a rollback query is executed. If this is an inner * transaction (nesting level > 1) the error flag is set, leaving the * rollback to the outermost transaction. * * This method always returns true. * * @see beginTransaction() * @see commit() * @return bool */ public function rollback() { if ($this->transactionNestingLevel <= 0) { $this->transactionNestingLevel = 0; throw new ezcDbTransactionException("rollback() called without previous beginTransaction()."); } if ($this->transactionNestingLevel == 1) { $this->db->rollback(); $this->transactionErrorFlag = false; // reset error flag } else { // set the error flag, so that if there is outermost commit // then ROLLBACK will be done instead of COMMIT $this->transactionErrorFlag = true; } $this->transactionNestingLevel--; return true; }
/** * Executes multiple SQL statements in a single transaction, each with its own parameters */ function tquery() { // sql statements in transaction $sqls = explode(";", rtrim(func_get_arg(0), ";")); // parameters, if any $params_list = array_slice(func_get_args(), 1); if (count($sqls) != count($params_list)) { apologize("sql error"); } static $handle; if (!isset($handle)) { try { // connect to database $handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD); // ensure that PDO::prepare returns false when passed invalid SQL $handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (Exception $e) { // trigger (big, orange) error trigger_error($e->getMessage(), E_USER_ERROR); exit; } } foreach ($sqls as $sql) { // prepare SQL statement if (($statements[] = $handle->prepare($sql)) === false) { trigger_error($handle->errorInfo()[2], E_USER_ERROR); exit; } } try { $handle->beginTransaction(); for ($i = 0; $i < count($statements); $i++) { $statements[$i]->execute($params_list[$i]); } $handle->commit(); } catch (Exception $e) { $handle->rollback(); trigger_error($e->getMessage(), E_USER_ERROR); return false; } }
public function writeAll($table) { $options = $this->getOptions(); $firstLine = current($table); $keys = '"' . implode('","', array_map('trim', array_keys($firstLine))) . '"'; $marks = implode(',', array_fill(0, count(array_keys($firstLine)), '?')); try { /* Insérer plusieurs enregistrements sur une base tout-ou-rien */ $sql = sprintf('INSERT INTO %s (%s) VALUES(%s)' . "\n", $options['table'], $keys, $marks); $sth = $this->dbh->prepare($sql); foreach ($table as $line) { $sth->execute(array_values($line)); } } catch (\PDOException $e) { if ($options['transaction']) { $this->dbh->rollback(); } throw new \Exception($e->getMessage()); } }
function save_signature($url, $client_info, $md5, $cvec) { $compressed_cvec = puzzle_compress_cvec($cvec); $words = split_into_words($cvec); $dbh = new PDO(DB_DSN); $dbh->beginTransaction(); try { $st = $dbh->prepare('DELETE FROM sentpictures WHERE url = :url'); $st->execute(array(':url' => $url)); $st = $dbh->prepare('SELECT id FROM pictures WHERE digest = :digest'); $st->execute(array(':digest' => $md5)); $picture_id = $st->fetchColumn(); $st->closeCursor(); $duplicate = TRUE; if ($picture_id === FALSE) { $duplicate = FALSE; $st = $dbh->prepare('INSERT INTO pictures (digest) VALUES (:digest)'); $st->execute(array(':digest' => $md5)); $picture_id = $dbh->lastInsertId('id'); } $st = $dbh->prepare('INSERT INTO sentpictures (url, sender, picture_id) ' . 'VALUES (:url, :sender, :picture_id)'); $st->execute(array(':url' => $url, ':sender' => $client_info, ':picture_id' => $picture_id)); if ($duplicate === TRUE) { $dbh->commit(); return TRUE; } $st = $dbh->prepare('INSERT INTO signatures (compressed_signature, picture_id) ' . 'VALUES(:compressed_signature, :picture_id)'); $st->execute(array(':compressed_signature' => $compressed_cvec, ':picture_id' => $picture_id)); $signature_id = $dbh->lastInsertId('id'); $st = $dbh->prepare('INSERT INTO words (pos_and_word, signature_id) ' . 'VALUES (:pos_and_word, :signature_id)'); foreach ($words as $u => $word) { $st->execute(array('pos_and_word' => chr($u) . puzzle_compress_cvec($word), 'signature_id' => $signature_id)); } $dbh->commit(); } catch (Exception $e) { var_dump($e); $dbh->rollback(); } return TRUE; }
/** * Execute une liste de requete dans une transaction et renvoi le nombre total de ligne affecté * si $lastInsertId est fourni il est rempli avec le dernier ID inséré * @param array $queryList [ ['SQL QUERY', ['PARAM'=>'VALUE', ...]], 'SQL QUERY', ... ] * @param int $lastInsertId * @throws \Exception * @throws \PDOException * @return int */ public function execInTransaction(array $queryList, &$lastInsertId = null) { try { if (!$this->_dbHandler) { $this->connect(); } $rowCount = 0; $this->_dbHandler->beginTransaction(); foreach ($queryList as $queryParam) { if (is_string($queryParam)) { $rowCount += $this->exec($queryParam, []); } elseif (is_array($queryParam)) { $rowCount += $this->exec($queryParam[0], $queryParam[1]); } } $this->_dbHandler->commit(); $lastInsertId = $this->_dbHandler->lastInsertId(); } catch (\PDOException $e) { $this->_dbHandler->rollback(); throw $e; } return $rowCount; }
/** * Drops whole table. * */ protected function dropTable() { if (!$this->db->beginTransaction()) { throw new PDOException($this->getLang('notransact')); } try { if (!$this->obtainLock($this->table, null, true, true)) { $this->render('<div class="error">' . $this->getLang('tablelocked') . '</div>'); $this->db->rollback(); return true; } if ($this->db->query('DROP TABLE ' . $this->table) === false) { throw new PDOException(sprintf($this->getLang('nodrop'), $this->table)); } $this->log('drop', $this->table); if (!$this->db->commit()) { throw new PDOException($this->getLang('dropcommit')); } } catch (PDOException $e) { $this->db->rollback(); throw $e; } }
/** * Rolls back a transaction. * This method is part of the transaction mechanism of * RedBeanPHP. All queries in a transaction are executed together. * In case of an error all commands will be rolled back so none of the * SQL in the transaction will affect the DB. Using transactions is * considered best practice. * This method has no return value. * * @return void */ public function FailTrans() { $this->connect(); $this->pdo->rollback(); }
/** * Rolls the transaction back */ public function rollback() { $this->pdo->rollback(); }
if ($ret == true) { $res = show_info('succ', '处理成功'); } else { $res = show_info('succ', '处理成功'); } echo json_encode($res); log_info("set friend action: send_notice_to_uid {$ret}"); return 0; } else { log_info("set friend action fail: 请选择执行的动作"); $res = show_info('fail', '请选择执行的动作'); echo json_encode($res); return 0; } } catch (PDOException $e) { $db->rollback(); log_info("set friend action fail, " . $e->getMessage()); $res = show_info('fail', $e->getMessage()); $res['localdes'] = $e->getMessage(); echo json_encode($res); return 1; } return 0; } else { log_info("set friend action fail: parameters error"); $res['status'] = 'fail'; $res['des'] = 'parameters error'; } echo json_encode($res); ?>
if (isset($ret[0]['login'])) { $_POST['error'] = "Login already exists."; header("Location: ../subscribe.php"); } else { $trans = 1; $pdo->beginTransaction(); $sql = "INSERT INTO wt_conf VALUES (?, ?, ?, ?);"; $pre = $pdo->prepare($sql); $pre->execute(array($user_name, $password, $e_mail, $token)); $pdo->commit(); $trans = 0; } } } catch (PDOException $error) { if ($trans) { $pdo->rollback(); } $_POST['error'] = "An error occured while connection to database"; $pdo = null; unset($error); header("Location: ../subscribe.php"); } $msg = 'Hello world! and welcome to Camagru, You have to validate your account with the link below : http://localhost:8080/Camagru/validate.php Enter the code :' . $token . ' Enter your login and password and let\'s take some pictures !!'; $msg = wordwrap($msg, 70, '<br />'); mail($e_mail, 'Confirm account Camagru', $msg);
$stmt->bindParam(':resourceID', $resourceID); $stmt->bindParam(':weekday', $weekday); $stmt->bindParam(':repeats', $repeats); $stmt->bindParam(':repeat_freq', $repeat_freq); $stmt->bindParam(':category_id', $category_id); $stmt->execute(); $last_id = $dbh->lastInsertId(); while ($startOfevent <= $endOfyear) { $dbh->query('SET NAMES utf8'); $stmt = $dbh->prepare("INSERT INTO events\n (title, start, end, resourceID, parent_id, repeat_freq, category_id)\n VALUES (:title, :start, :end, :resourceID, :parent_id, :repeat_freq, :category_id)"); $stmt->bindParam(':title', $title); $stmt->bindParam(':start', $start); $stmt->bindParam(':end', $end); $stmt->bindParam(':resourceID', $resourceID); $stmt->bindParam(':parent_id', $last_id); $stmt->bindParam(':repeat_freq', $repeat_freq); $stmt->bindParam(':category_id', $category_id); $stmt->execute(); $start_date = strtotime($start . '+' . $repeat_freq . 'DAYS'); $end_date = strtotime($end . '+' . $repeat_freq . 'DAYS'); $start = date("Y-m-d H:i", $start_date); $end = date("Y-m-d H:i", $end_date); $startOfevent = date("Y-m-d", strtotime($startOfevent . '+' . $repeat_freq . 'DAYS')); $firephp->log("weszło do pętli"); } $dbh->commit(); } catch (Exception $e) { $dbh->rollback(); } } //header ("location: ../");
/** * Load the sql file and then execute it. * * {@inheritdoc} * * @throws BuildException */ public function main() { // Set a default fetchmode if none was specified // (We're doing that here to prevent errors loading the class is PDO is not available.) if ($this->fetchMode === null) { $this->fetchMode = PDO::FETCH_ASSOC; } // Initialize the formatters here. This ensures that any parameters passed to the formatter // element get passed along to the actual formatter object foreach ($this->formatters as $fe) { $fe->prepare(); } $savedTransaction = array(); for ($i = 0, $size = count($this->transactions); $i < $size; $i++) { $savedTransaction[] = clone $this->transactions[$i]; } $savedSqlCommand = $this->sqlCommand; $this->sqlCommand = trim($this->sqlCommand); try { if ($this->srcFile === null && $this->sqlCommand === "" && empty($this->filesets) && empty($this->filelists) && count($this->transactions) === 0) { throw new BuildException("Source file or fileset/filelist, " . "transactions or sql statement " . "must be set!", $this->location); } if ($this->srcFile !== null && !$this->srcFile->exists()) { throw new BuildException("Source file does not exist!", $this->location); } // deal with the filesets foreach ($this->filesets as $fs) { $ds = $fs->getDirectoryScanner($this->project); $srcDir = $fs->getDir($this->project); $srcFiles = $ds->getIncludedFiles(); // Make a transaction for each file foreach ($srcFiles as $srcFile) { $t = $this->createTransaction(); $t->setSrc(new PhingFile($srcDir, $srcFile)); } } // process filelists foreach ($this->filelists as $fl) { $srcDir = $fl->getDir($this->project); $srcFiles = $fl->getFiles($this->project); // Make a transaction for each file foreach ($srcFiles as $srcFile) { $t = $this->createTransaction(); $t->setSrc(new PhingFile($srcDir, $srcFile)); } } // Make a transaction group for the outer command $t = $this->createTransaction(); if ($this->srcFile) { $t->setSrc($this->srcFile); } $t->addText($this->sqlCommand); $this->conn = $this->getConnection(); try { $this->statement = null; // Initialize the formatters. $this->initFormatters(); try { // Process all transactions for ($i = 0, $size = count($this->transactions); $i < $size; $i++) { if (!$this->isAutocommit()) { $this->log("Beginning transaction", Project::MSG_VERBOSE); $this->conn->beginTransaction(); } $this->transactions[$i]->runTransaction(); if (!$this->isAutocommit()) { $this->log("Committing transaction", Project::MSG_VERBOSE); $this->conn->commit(); } } } catch (Exception $e) { $this->closeConnection(); throw $e; } } catch (IOException $e) { if (!$this->isAutocommit() && $this->conn !== null && $this->onError == "abort") { try { $this->conn->rollback(); } catch (PDOException $ex) { } } $this->closeConnection(); throw new BuildException($e->getMessage(), $this->location); } catch (PDOException $e) { if (!$this->isAutocommit() && $this->conn !== null && $this->onError == "abort") { try { $this->conn->rollback(); } catch (PDOException $ex) { } } $this->closeConnection(); throw new BuildException($e->getMessage(), $this->location); } // Close the formatters. $this->closeFormatters(); $this->log($this->goodSql . " of " . $this->totalSql . " SQL statements executed successfully"); } catch (Exception $e) { $this->transactions = $savedTransaction; $this->sqlCommand = $savedSqlCommand; $this->closeConnection(); throw $e; } // finally { $this->transactions = $savedTransaction; $this->sqlCommand = $savedSqlCommand; $this->closeConnection(); }
/** * rollback - Overloading default method */ public function rollback() { parent::rollback(); $this->activeTransaction = false; }
public function rollback() { $this->mRetryCounter = 0; return parent::rollback(); }
private function insertStatsToDb($data) { $statsDbHostName = $_SERVER['STATS_DB_HOST']; $statsDbName = $_SERVER['STATS_DB_NAME']; $statsDbUser = $_SERVER['STATS_DB_USER']; $statsDbPass = $_SERVER['STATS_DB_PASS']; $dbh = null; try { $dbh = new PDO("mysql:host={$statsDbHostName};dbname={$statsDbName}", $statsDbUser, $statsDbPass); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh->beginTransaction(); $stmt = $dbh->prepare("INSERT IGNORE INTO editorstats (wiki_id, revision_id, editor, user_groups)\n \t\t\t\tVALUES (:wiki_id, :revision_id, :editor, :user_groups)"); $stmt->bindParam(':wiki_id', $wiki_id); $stmt->bindParam(':revision_id', $revision_id); $stmt->bindParam(':editor', $editor); $stmt->bindParam(':user_groups', $user_groups); foreach ($data as $rev) { $wiki_id = $rev['wiki_id']; $revision_id = $rev['revision_id']; $editor = $rev['editor']; $user_groups = $rev['user_groups']; $stmt->execute(); } $dbh->commit(); } catch (PDOException $error) { $dbh->rollback(); print $error->getMessage(); } }