mysqli::begin_transaction

mysqli_begin_transaction

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

mysqli::begin_transaction -- mysqli_begin_transactionStarts a transaction

Description

Object-oriented style

publicmysqli::begin_transaction(int$flags = 0, ?string$name = null): bool

Procedural style:

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

Begins a transaction. Requires the InnoDB engine (it is enabled by default). For additional details about how MySQL transactions work, see » http://dev.mysql.com/doc/mysql/en/commit.html.

Parameters

mysql

Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

flags

Valid flags are:

  • MYSQLI_TRANS_START_READ_ONLY: Start the transaction as "START TRANSACTION READ ONLY". Requires MySQL 5.6 and above.

  • MYSQLI_TRANS_START_READ_WRITE: Start the transaction as "START TRANSACTION READ WRITE". Requires MySQL 5.6 and above.

  • MYSQLI_TRANS_START_WITH_CONSISTENT_SNAPSHOT: Start the transaction as "START TRANSACTION WITH CONSISTENT SNAPSHOT".

name

Savepoint name for the transaction.

Return Values

Returns true on success or false on failure.

Changelog

VersionDescription
8.0.0name is now nullable.

Examples

Example #1 mysqli::begin_transaction() example

Object-oriented style

<?php


mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");


$mysqli->query("CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"
);


$mysqli->begin_transaction();

try {

$mysqli->query("INSERT INTO language(Code, Speakers) VALUES ('DE', 42000123)");


$language_code = 'FR';
$native_speakers = 'Unknown';
$stmt = $mysqli->prepare('INSERT INTO language(Code, Speakers) VALUES (?,?)');
$stmt->bind_param('ss', $language_code, $native_speakers);
$stmt->execute();


$mysqli->commit();
} catch (
mysqli_sql_exception $exception) {
$mysqli->rollback();

throw
$exception;
}

Procedural style

<?php


mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");


mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"
);


mysqli_begin_transaction($mysqli);

try {

mysqli_query($mysqli, "INSERT INTO language(Code, Speakers) VALUES ('DE', 42000123)");


$language_code = 'FR';
$native_speakers = 'Unknown';
$stmt = mysqli_prepare($mysqli, 'INSERT INTO language(Code, Speakers) VALUES (?,?)');
mysqli_stmt_bind_param($stmt, 'ss', $language_code, $native_speakers);
mysqli_stmt_execute($stmt);


mysqli_commit($mysqli);
} catch (
mysqli_sql_exception $exception) {
mysqli_rollback($mysqli);

throw
$exception;
}

Notes

Note:

This function does not work with non transactional table types (like MyISAM or ISAM).

See Also

To Top