function sql_transaction($status = 'begin') { switch ($status) { case 'begin': $result = @mysqli_autocommit($this->db_connect_id, false); $this->transaction = true; break; case 'commit': $result = @mysqli_commit($this->db_connect_id); @mysqli_autocommit($this->db_connect_id, true); $this->transaction = false; if (!$result) { @mysqli_rollback($this->db_connect_id); @mysqli_autocommit($this->db_connect_id, true); } break; case 'rollback': $result = @mysqli_rollback($this->db_connect_id); @mysqli_autocommit($this->db_connect_id, true); $this->transaction = false; break; default: $result = true; } return $result; }
public function insertItems(Items $items) { $con = self::openConnection(); $affected = 0; mysqli_begin_transaction($con); $stm = mysqli_stmt_init($con); $sql = "INSERT INTO category VALUES (?, ?, ?)"; mysqli_stmt_prepare($stm, $sql); foreach ($items->getItems() as $item) { $code = $item->getCode(); $name = $item->getName(); $parent = $item->getParent() == null ? null : $item->getParent()->getCode(); mysqli_stmt_bind_param($stm, 'sss', $code, $name, $parent); mysqli_stmt_execute($stm); if (mysqli_affected_rows($con) == 1) { $affected++; } } if ($affected > 0) { mysqli_commit($con); } else { mysqli_rollback($con); } return $affected; }
public function salvarProduto($produto, $preco) { $codigo = $produto->getCodigo(); $nome = $produto->getNome(); $descricao = $produto->getDescricao(); $imagem = $produto->getUrlImagem(); $compra = $preco->getCompra(); $venda = $preco->getVenda(); $revenda = $preco->getReVenda(); /* * conecta o banco de dados */ $con = new JqsConnectionFactory(); $link = $con->conectar(); $query = "INSERT INTO tb_produtos (codigo_produto, nome_produto, descricao_produto, url_imagem) \n\t\tvalues('{$codigo}', '{$nome}', '{$descricao}', '{$imagem}')"; $query2 = "INSERT INTO tb_precos (preco_compra, preco_venda, preco_revenda, id_produto_preco) \n\t\tvalues('{$compra}', '{$venda}', '{$revenda}', last_insert_id() )"; try { mysqli_autocommit($link, FALSE); mysqli_query($link, $query) or die(mysqli_error($link) . "Produto"); mysqli_query($link, $query2) or die(mysqli_error($link) . "Preço"); mysqli_commit($link); mysqli_autocommit($link, TRUE); } catch (Exception $e) { mysqli_rollback($link); echo $e; } }
public function insertItems(Items $items) { $con = self::openConnection(); $affected = 0; mysqli_begin_transaction($con); $stm = mysqli_stmt_init($con); $sql = "INSERT INTO product VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; mysqli_stmt_prepare($stm, $sql); foreach ($items->getItems() as $item) { $code = $item->getCode(); $articul = $item->getArticul(); $name = $item->getName(); $bmuID = $item->getBasicMeasurementUnit() == null ? null : $item->getBasicMeasurementUnit()->getId(); $price = $item->getPrice(); $curID = $item->getCurrency() == null ? null : $item->getCurrency()->getId(); $muID = $item->getMeasurementUnit() == null ? null : $item->getMeasurementUnit()->getId(); $parent = $item->getParent() == null ? null : $item->getParent()->getCode(); mysqli_stmt_bind_param($stm, 'sssdddds', $code, $articul, $name, $bmuID, $price, $curID, $muID, $parent); mysqli_stmt_execute($stm); if (mysqli_affected_rows($con) == 1) { $affected++; } } if ($affected > 0) { mysqli_commit($con); } else { mysqli_rollback($con); } return $affected; }
public function finalizeTransaction($transactionComplete) { if (!$transactionComplete) { mysqli_rollback($this->dbConnection); } else { mysqli_commit($this->dbConnection); } }
public function Rollback() { if ($this->in_transazione) { return mysqli_rollback($this->conn); } else { return 0; } }
public function rollback() { if (mysqli_rollback($this->connection)) { mysqli_autocommit($this->connection, $this->autoCommit = true); } else { throw new Sabel_Db_Exception_Driver(mysql_error($this->connection)); } }
public function encerraTransacao($lErro) { $this->lTransacao = false; if ($lErro) { $lRetorno = mysqli_rollback($this->conn); } else { $lRetorno = mysqli_commit($this->conn); } $this->fecharConexao(); return $lRetorno; }
/** * DB transaction rollback * this method is private * @return boolean */ function _rollback($transactionLevel = 0) { $connection = $this->_getConnection('master'); $point = $transactionLevel - 1; if ($point) { $this->_query("ROLLBACK TO SP" . $point, $connection); } else { mysqli_rollback($connection); $this->setQueryLog(array('query' => 'ROLLBACK')); } return true; }
function commandDataBase($sql) { $conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname); if ($conn->connect_error) { die('Connection failed: ' . $conn->connect_error); } mysqli_autocommit($conn, FALSE); if ($conn->query($sql) === TRUE) { mysqli_commit($conn); return true; } else { mysqli_rollback($conn); return false; } $conn->close(); }
function updateRecord($arrayValues, $table, $condition, $autoCommit = "yes") { include_once 'connection.php'; mysqli_autocommit($conn, false); $table_value = ""; if (empty($arrayValues)) { echo "Incomplete Parameters Passed"; die; } if (!is_array($arrayValues)) { echo "Parameter Passed is not an Array"; return false; } foreach ($arrayValues as $ind => $v) { //$table_value .= $ind . "= '" . $v . "',"; $firstChar = substr($v, 0, 1); if ($firstChar == '(') { $table_value .= $ind . "= " . $v . ","; } else { $table_value .= $ind . "= '" . $v . "',"; } } $table_value = substr($table_value, 0, -1); try { $sql = "UPDATE {$table} SET {$table_value} WHERE {$condition}"; //Check if inserted to table, if not rollback mysqli_query($conn, $sql); if (mysqli_errno($conn)) { $errno = mysqli_errno($conn); mysqli_rollback($conn); return "error"; } else { if ($autoCommit == "yes") { mysqli_commit($conn); return true; } else { return true; } } } catch (Exception $e) { mysqli_rollback($conn); return "error"; } }
/** * SQL Transaction * @access private */ function _sql_transaction($status = 'begin') { switch ($status) { case 'begin': return @mysqli_autocommit($this->db_connect_id, false); break; case 'commit': $result = @mysqli_commit($this->db_connect_id); @mysqli_autocommit($this->db_connect_id, true); return $result; break; case 'rollback': $result = @mysqli_rollback($this->db_connect_id); @mysqli_autocommit($this->db_connect_id, true); return $result; break; } return true; }
/** * Transaction style - runs queries in order * * @since 08.05.2011 * Refactored for using $this::mysqli_connection instead of mysqli_init/mysqli_close */ public function executeMultiNoresSQL(&$queryArry) { $link = $this->getMysqliConnection(); /* set autocommit to off */ mysqli_autocommit($link, FALSE); $all_query_ok = true; //do queries foreach ($queryArry as $query) { if (!mysqli_real_query($link, $query)) { $all_query_ok = false; } } if ($all_query_ok) { /* commit queries */ mysqli_commit($link); } else { /* Rollback */ mysqli_rollback($link); } /* set autocommit to on */ mysqli_autocommit($link, TRUE); return $all_query_ok; }
public function insertUnits(Units $units) { $con = self::openConnection(); $affected = 0; mysqli_begin_transaction($con); $stm = mysqli_stmt_init($con); $sql = "INSERT INTO currency (code) VALUE (?)"; mysqli_stmt_prepare($stm, $sql); foreach ($units->getUnits() as $unit) { $code = $unit->getCode(); mysqli_stmt_bind_param($stm, 's', $code); mysqli_stmt_execute($stm); if (mysqli_affected_rows($con) == 1) { $affected++; } } if ($affected > 0) { mysqli_commit($con); } else { mysqli_rollback($con); } return $affected; }
public function salvarCliente($cliente, $endereco) { $nome = $cliente->getNome(); $fone = $cliente->getFone(); $email = $cliente->getEmail(); $instagran = $cliente->getInstagran(); $indicacao = $cliente->getIndicacao(); $tipo = $cliente->getTipo(); $whatsapp = $cliente->getWhatsapp(); $aniversario = $cliente->getAniversario(); $facebook = $cliente->getFacebook(); //$endereco = new Endereco(); $logradouro = $endereco->getLogradouro(); $numero = $endereco->getNumero(); $bairro = $endereco->getBairro(); $cidade = $endereco->getCidade(); $estado = $endereco->getEstado(); $cep = $endereco->getCep(); $complemento = $endereco->getComplemento(); /* * conecta o banco de dados */ $con = new JqsConnectionFactory(); $link = $con->conectar(); $query = "INSERT INTO tb_clientes (nome_cliente, fone_cliente, email_cliente, instagran_cliente, indicacao_cliente, tipo_cliente, whatsapp_cliente, aniversario_cliente, facebook_cliente) \n\t\tvalues('{$nome}', '{$fone}', '{$email}', '{$instagran}', '{$indicacao}', '{$tipo}', '{$whatsapp}', '{$aniversario}', '{$facebook}')"; $query2 = "INSERT INTO tb_enderecos (logradouro_endereco, numero_endereco, bairro_edereco, cidade_endereco, \n\t\testado_endereco, cep_endereco, complemento_endereco, id_cliente_endereco) values('{$logradouro}','{$numero}',\n\t\t'{$bairro}', '{$cidade}', '{$estado}', '{$cep}', '{$complemento}', last_insert_id())"; try { mysqli_autocommit($link, FALSE); mysqli_query($link, $query) or die(mysqli_error($link) . "cliente"); mysqli_query($link, $query2) or die(mysqli_error($link) . "endereço"); mysqli_commit($link); mysqli_autocommit($link, TRUE); } catch (Exception $e) { mysqli_rollback($link); echo $e; } }
public function executeMultiNoresSQL(&$queryArry) { $link = mysqli_init(); if (!$link) { throw new DBAdapter2Exception("mysqli_init failed"); } if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) { throw new DBAdapter2Exception("Setting MYSQLI_OPT_CONNECT_TIMEOUT failed"); } if (!mysqli_real_connect($link, $this->host, $this->username, $this->password, $this->schema)) { throw new DBAdapter2Exception('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } if (!mysqli_set_charset($link, $this->charset)) { throw new DBAdapter2Exception('Error loading character set ' . $this->charset . ' - ' . mysqli_error($link)); } /* set autocommit to off */ mysqli_autocommit($link, FALSE); $all_query_ok = true; //do queries foreach ($queryArry as $query) { if (!mysqli_real_query($link, $query)) { $all_query_ok = false; } } if ($all_query_ok) { /* commit queries */ mysqli_commit($link); } else { /* Rollback */ mysqli_rollback($link); } /* set autocommit to on */ mysqli_autocommit($link, TRUE); mysqli_close($link); return $all_query_ok; }
public static function rollback() { return mysqli_rollback(self::$conn); }
$qty = $item['quantity']; $price = $item['price']; mysqli_stmt_execute($stmt); $affected += mysqli_stmt_affected_rows($stmt); } // Close this prepared statement: mysqli_stmt_close($stmt); // Report on the success.... if ($affected == count($_SESSION['cart'])) { // Whohoo! // Commit the transaction: mysqli_commit($dbc); // Clear the cart: unset($_SESSION['cart']); // Message to the customer: echo '<p>Thank you for your order. You will be notified when the items ship.</p>'; // Send emails and do whatever else. } else { // Rollback and report the problem. mysqli_rollback($dbc); echo '<p>Your order could not be processed due to a system error. You will be contacted in order to have the problem fixed. We apologize for the inconvenience.</p>'; // Send the order information to the administrator. } } else { // Rollback and report the problem. mysqli_rollback($dbc); echo '<p>Your order could not be processed due to a system error. You will be contacted in order to have the problem fixed. We apologize for the inconvenience.</p>'; // Send the order information to the administrator. } mysqli_close($dbc); include 'includes/footer.html';
public function CrearUsuario($nombreU, $contraU, $programaU, $descPU) { // Valido si ya existe ese programa // $cadenaConsulta = "SELECT * from programas where nombre='" . utf8_decode($programaU) . "'"; $repetido = $this->validarRepetido($cadenaConsulta); if ($repetido) { return json_encode(new Respuesta("ERROR", "REPETIDO PROGRAMA")); } else { // Valido si ya existe ese usuario // $existeUsuario = $this->validarNombreUsuario($nombreU); $numFilas = mysql_num_rows($existeUsuario); if ($numFilas > 0) { return json_encode(new Respuesta("ERROR", "REPETIDO USUARIO")); } else { try { $this->conectarTran(); mysqli_autocommit($this->db_conexionTran, false); $flag = true; // Creo Usuario // $cadenaInsertar = "Insert into usuarios (nombre, contraseña,activo,categoria) values ('" . $nombreU . "','" . $contraU . "',1,2)"; $flag = mysqli_query($this->db_conexionTran, $cadenaInsertar); if (!$flag) { mysqli_rollback($this->db_conexionTran); throw new Exception('Error MySQL'); } else { // Creo programa // $cadenaInsertar = "Insert into programas (id, nombre, descripcion,activo,usuario) values ( '','" . utf8_decode($programaU) . "','" . utf8_decode($descPU) . "',1,'" . $nombreU . "')"; $flag = mysqli_query($this->db_conexionTran, $cadenaInsertar); if (!$flag) { mysqli_rollback($this->db_conexionTran); throw new Exception('Error MySQL'); } else { mysqli_commit($this->db_conexionTran); return json_encode(new Respuesta("OK", "")); } } } catch (exception $e) { throw new Exception('Error MySQL'); } } } }
error_reporting(-1); mysqli_autocommit($db, false); $errorstr = ""; $status = true; $studentgroupstodelete = array(); if (isset($_POST['studentgroupstodelete'])) { $studentgroupstodelete = $_POST['studentgroupstodelete']; } $query = "delete from groups_students where groupid="; foreach ($studentgroupstodelete as $groupid) { $groupid = strip_tags(mysqli_real_escape_string($db, $groupid)); $res = mysqli_query($db, $query . "'{$groupid}'"); // echo $query.$groupid; if (!$res) { $status = false; $errorstr = "Error in delete query"; goto end; } } end: if ($status) { mysqli_commit($db); mysqli_close($db); header("Location: ./../view_studentgroups.php?prev=done&msg=Student groups deleted successfully"); } else { mysqli_rollback($db); mysqli_close($db); // echo "$errorstr"; header("Location: ./../view_studentgroups.php?prev=fail&error=Couldn't delete student groups: {$errorstr}"); } }
/** * Insert activity log event for images which are resized. */ $log_sql = "INSERT INTO for_log\n (`event`, `table`, tag, object, user, created, acknowledged)\n VALUES\n ('upload',\n 'extras',\n '{$_POST['path']}.jpg',\n '{$_POST['subtype']}',\n '{$user['email']}',\n now(),\n null);"; $log_result = mysqli_query($link, $log_sql); if (!$log_result) { $events['mysql']['result'] = false; $events['mysql']['code'] = mysqli_errno($link); $events['mysql']['error'] = mysqli_error($link); goto end; } break; } /** * Only accept the transaction, if all results are successuful. * Note, on rollback auto-increment for successful transfers is not reset. */ if ($log_result) { mysqli_commit($link); $events['mysql']['result'] = true; } else { mysqli_rollback($link); } end: /** * Send the response back to the browser in JSON format. * And finally close the connection. */ echo json_encode(array('events' => $events)); mysqli_close($link); }
function modificarEstatusSocio($idUsuarioGym, $estatus, $sucursal) { //Creamos la conexión con la función anterior $conexion = obtenerConexion(); mysqli_set_charset($conexion, "utf8"); //formato de datos utf8 if ($conexion) { /* deshabilitar autocommit para poder hacer un rollback*/ mysqli_autocommit($conexion, FALSE); //Lo primero que haremos será obtener el id del socio, de acuerdo con el idUsuarioGym que se haya enviado $sql = "SELECT So_Id, Id_UsuarioGym FROM socio where Id_UsuarioGym={$idUsuarioGym};"; if ($result = mysqli_query($conexion, $sql)) { // Ejecutamos la consulta para obtener el id del socio while ($row = mysqli_fetch_array($result)) { //Obtenemos los resultados $idSocio = $row["So_Id"]; } $sql2 = "UPDATE usuariogimnasio SET `Estatus`={$estatus} WHERE `UG_Id`={$idUsuarioGym};"; if ($result2 = mysqli_query($conexion, $sql2)) { //Ejecutamos la sentencia para actualizar el estatus del gimnasio //Si se actualizó correctamente el estatus del UsuarioGimnasio, procederemos a actualizar el estatus del Socio $sql3 = "UPDATE `socio` SET `Estatus`={$estatus} WHERE `So_Id`={$idSocio};"; if ($result3 = mysqli_query($conexion, $sql3)) { //Ejecutamos la sentencia para actualizar el estatus del socio mysqli_commit($conexion); $response["Socios"] = $this->getSociosBySucursalId($sucursal); $response["success"] = 0; $response["message"] = 'Se ha modificado correctamente el estatus del socio'; } else { mysqli_rollback($conexion); $response["success"] = 5; $response["message"] = 'Se presentó un error al actualizar el estatus del Socio'; } } else { mysqli_rollback($conexion); $response["success"] = 4; $response["message"] = 'Se presentó un error al actualizar el estatus del UsuarioGimnasio'; } } else { // Se presentó un error al generar la consulta del id del socio $response["success"] = 1; $response["message"] = 'Se presentó un error al consultar el id del socio'; } desconectar($conexion); } else { $response["success"] = 3; $response["message"] = 'Se presentó un error en la conexión con la base de datos'; } return $response; //devolvemos el array }
/** * This function rollbacks a transaction. * * @access public * @override * @throws Throwable_SQL_Exception indicates that the executed * statement failed * * @see http://www.php.net/manual/en/mysqli.rollback.php */ public function rollback() { if (!$this->is_connected()) { throw new Throwable_SQL_Exception('Message: Failed to rollback SQL transaction. Reason: Unable to find connection.'); } $command = @mysqli_rollback($this->resource); if ($command === FALSE) { throw new Throwable_SQL_Exception('Message: Failed to rollback SQL transaction. Reason: :reason', array(':reason' => @mysqli_error($this->resource))); } @mysqli_autocommit($this->resource, TRUE); $this->sql = 'ROLLBACK;'; }
/** * 回滚 * * 当开启事务处理后,有需要的时候进行回滚 * * @return boolean */ public function rollback() { return mysqli_rollback($this->uConn); }
public function rollbackTransaction() { return mysqli_rollback($this->getConnection()->getHandle()); }
echo "Error details: " . mysqli_error($dbConnection) . "."; } //calculating new card amount of recipient $new_amount_recipient = (double) $current_amount_r + (double) $transfer_amount; //query variables for updating card amounts of sender and recipient $query2 = "UPDATE users set card_amount='{$new_amount_sender}' where user='******';"; $query3 = "UPDATE users set card_amount='{$new_amount_recipient}' where user='******';"; //third query execution and its result processing $result = mysqli_query($dbConnection, $query2); if (!$result) { $flag = false; echo "Error details: " . mysqli_error($dbConnection) . "."; } //fourth query execution and its result processing $result = mysqli_query($dbConnection, $query3); if (!$result) { $flag = false; echo "Error details: " . mysqli_error($dbConnection) . "."; } //if all previous checkings were true - commit transaction if ($flag) { mysqli_commit($dbConnection); //creating div with successful results echo "\n\t<div id=\"transfer_res\">\n\t<p>\n\tThe transfer was executed successfully.\n\t</p>\n\t</div>\n\t"; } else { mysqli_rollback($dbConnection); //creating div with unsuccessful results echo "\n\t<div id=\"transfer_res\">\n\t<p>\n\tThe transfer was failed.\n\t</p>\n\t</div>\n\t"; } //closing connection mysqli_close($dbConnection);
protected function _performRollback() { return mysqli_rollback($this->link); }
// set autocommit to off mysqli_autocommit($mysqli_answer, FALSE); // escape the inputs $messageid_todb = mysqli_real_escape_string($mysqli_answer, $messageid); $ticketid_todb = mysqli_real_escape_string($mysqli_answer, $ticketid); $message_todb = mysqli_real_escape_string($mysqli_answer, $message); $set_status_todb = mysqli_real_escape_string($mysqli_answer, $set_status); // Insert some values $sql_answer = mysqli_query($mysqli_answer, "INSERT INTO cms_answers (messageid, ticketid, message, ufrom, userlevel, time) VALUES ('{$messageid_todb}','{$ticketid_todb}','{$message_todb}','{$username_form}','2',now())"); $sql_answer2 = mysqli_query($mysqli_answer, "UPDATE cms_tickets SET status='{$set_status_todb}' WHERE ticketid='{$ticketid_todb}'"); if ($sql_answer && $sql_answer2) { // commit transaction mysqli_commit($mysqli_answer); echo "<div class=\"success\">" . lang('ADMIN_ENTYSUCC') . "</div>"; } else { mysqli_rollback($mysqli_answer); echo "<div class=\"error\">" . lang('TICKET_ERR') . "</div>"; } mysqli_close($mysqli_answer); } // connect to db $mysqli = getConnected("account"); $res = mysqli_query($mysqli, "SELECT * FROM cms_tickets WHERE id='" . $id . "'"); while ($row = mysqli_fetch_array($res)) { // set form variables $form_id = $row["id"]; $form_tid = $row["ticketid"]; // Get status if ($row["status"] == "1") { $statusc = "<div class=\"open\">" . lang('TICKET_OPEN') . "</div>"; } elseif ($row["status"] == "2") {
function sqlCommRollChanges($sql_error, $sqlLink, $pcn) { $response = ""; if ($sql_error == 0) { mysqli_commit($sqlLink); $response['message'] = "The course " . $pcn . " was successfully added to your watch-list"; } else { mysqli_rollback($sqlLink); $response['message'] = "There was an error processing your request. Please try again later."; } echo json_encode($response); exit(0); }
public function rollbackTransaction() { if ($this->logging_transaction === true) { $this->logging_transaction = false; $this->logging_transaction_action = false; } if ($this->use_transactions === true) { $result = @mysqli_rollback($this->link); @mysqli_autocommit($this->link, true); return $result; } return false; }