PHP 8.3.4 Released!

mysqli::commit

mysqli_commit

(PHP 5, PHP 7, PHP 8)

mysqli::commit -- mysqli_commitФиксирует текущую транзакцию

Описание

Объектно-ориентированный стиль

public mysqli::commit(int $flags = 0, ?string $name = null): bool

Процедурный стиль

mysqli_commit(mysqli $mysql, int $flags = 0, ?string $name = null): bool

Фиксирует транзакцию для установленного соединения с базой данных.

Список параметров

mysql

Только для процедурного стиля: объект mysqli, который вернула функция mysqli_connect() или функция mysqli_init().

flags

Битмаска констант MYSQLI_TRANS_COR_*.

name

Если передан, то выполняется COMMIT/*name*/.

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае ошибки.

Ошибки

Если уведомления об ошибках mysqli включены (MYSQLI_REPORT_ERROR) и запрошенная операция не удалась, выдаётся предупреждение. Если, кроме того, установлен режим MYSQLI_REPORT_STRICT, вместо этого будет выброшено исключение mysqli_sql_exception.

Список изменений

Версия Описание
8.0.0 name теперь допускает значение null.

Примеры

Смотрите пример использования в разделе mysqli::begin_transaction().

Примечания

Замечание:

Функция не работает с нетранзакционными типами таблиц (такими как MyISAM или ISAM).

Смотрите также

  • mysqli_autocommit() - Включает или отключает автоматическую фиксацию изменений базы данных
  • mysqli_begin_transaction() - Стартует транзакцию
  • mysqli_rollback() - Откат текущей транзакции
  • mysqli_savepoint() - Установите именованную точку сохранения транзакции

add a note

User Contributed Notes 6 notes

up
27
mvanlamz
14 years ago
Please note that calling mysqli::commit() will NOT automatically set mysqli::autocommit() back to 'true'.

This means that any queries following mysqli::commit() will be rolled back when your script exits.
up
22
snchzantonio at gmail dot com
10 years ago
I never recomend to use the ? with only one value variant like: $var = expression ? $var : other_value or $var = expression ? null : other_value ,and php suport Exception catchin so,use it :)

here my opinion abut lorenzo's post:

<?php

//variants combined

$mysqli->autocommit(FALSE);

try{

$mysqli->query("INSERT INTO myCity (id) VALUES (100)") or throw new Exception('error!');

// or we can use

if( !$mysqli->query("INSERT INTO myCity (id) VALUES (200)"){
throw new
Exception('error!');
}

}catch(
Exception $e ){
$mysqli->rollback();
}
$mysqli->commit();

?>
up
19
Lorenzo - webmaster AT 4tour DOT it
15 years ago
This is an example to explain the powerful of the rollback and commit functions.
Let's suppose you want to be sure that all queries have to be executed without errors before writing data on the database.
Here's the code:

<?php
$all_query_ok
=true; // our control variable

//we make 4 inserts, the last one generates an error
//if at least one query returns an error we change our control variable
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (200)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (300)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false; //duplicated PRIMARY KEY VALUE

//now let's test our control variable
$all_query_ok ? $mysqli->commit() : $mysqli->rollback();

$mysqli->close();
?>

hope to be helpful!
up
2
NoMan2000
8 years ago
This is to clarify the Flags parameters and what they mean:

MYSQLI_TRANS_COR_AND_CHAIN:

Appends "AND CHAIN" to mysqli_commit or mysqli_rollback.

MYSQLI_TRANS_COR_AND_NO_CHAIN:

Appends "AND NO CHAIN" to mysqli_commit or mysqli_rollback.

MYSQLI_TRANS_COR_RELEASE:

Appends "RELEASE" to mysqli_commit or mysqli_rollback.

MYSQLI_TRANS_COR_NO_RELEASE:

Appends "NO RELEASE" to mysqli_commit or mysqli_rollback.

To clarify those options:

The AND CHAIN clause causes a new transaction to begin as soon as the current one ends, and the new transaction has the same isolation level as the just-terminated transaction.

The RELEASE clause causes the server to disconnect the current client session after terminating the current transaction.
up
-1
zattechnology at gmail dot com
4 years ago
When you have alot of transactions to make, say you are applying inserting items to the database from a loop, it will be better to use the mysqli_commit for this kind of process as it will only hit the database once.

//Wrong way
Example 1:

$con = mysqli_connect("host", "username", "password", "database") or die("Could not establish connection to database");

$users = ["chris", "james", "peter", "mark", "joe", "alice", "bob"]

for($i=0; $i<count($users); $i++){
$user= $users[$i];
$query = mysqli_query($con, "INSERT INTO users (username) VALUES ('$user') ");
}

//Correct Way
Example 2

$con = mysqli_connect("host", "username", "password", "database") or die("Could not establish connection to database");

$users = ["chris", "james", "peter", "mark", "joe", "alice", "bob"]

//Turn off autocommit
mysqli_autocommit($con, FALSE)

//Make some transactions
for($i=0; $i<count($users); $i++){
$user= $users[$i];
$query = mysqli_query($con, "INSERT INTO users (username) VALUES ('$user') ");
}

//Make a one-time hit to the database
mysqli_commit($con)

As with the Example 1, since we had 7 items in the list, this means that their will be a 7 times hit to our database which can really affect performance. But with the Example 2, since we already turned off autocommit this means that the transactions will be queued ontill will explicitly call mysqli_commit($con)
up
-17
Bob Johnson
14 years ago
The compactness of Lorenzo's code is admirable.
However, it is a good idea to also check $mysqli->affected_rows to make sure that the INSERT statement did not fail.

<?php
$result_query
= @mysqli_query($query, $connect);
if ((
$result_query == false) &&
(
mysqli_affected_rows($connect) == 0))
{
// verify the query executed completely and verify that it
// had impact on the table

$success = false;

// here also, the developer could choose to add a ROLLBACK
// statement
}
?>
To Top