(PHP 5 >= 5.5.0, PHP 7, PHP 8)
mysqli::begin_transaction -- mysqli_begin_transaction — Démarre une transaction
Style orienté objet
Style procédural:
Commence une transaction. Nécessite le moteur InnoDB (il est actif par défaut). Pour plus de détails sur le fonctionnement des transactions MySQL, voir » http://dev.mysql.com/doc/mysql/en/commit.html.
mysql
Seulement en style procédural : Un objet mysqli retourné par la fonction mysqli_connect() ou mysqli_init().
flags
Les drapeaux valides sont :
MYSQLI_TRANS_START_READ_ONLY
: Commence la transaction comme "START TRANSACTION READ ONLY". Nécessite MySQL 5.6 ou supérieur.
MYSQLI_TRANS_START_READ_WRITE
: Commence la transaction comme "START TRANSACTION READ WRITE". Nécessite MySQL 5.6 et supérieur.
MYSQLI_TRANS_START_WITH_CONSISTENT_SNAPSHOT
: Commence la transaction comme "START TRANSACTION WITH CONSISTENT SNAPSHOT".
name
Nom du point de sauvegarde pour la transaction.
Version | Description |
---|---|
8.0.0 | name est désormais nullable. |
Exemple #1 Exemple avec mysqli::begin_transaction()
Style orienté objet
<?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;
}
Style procédural
<?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;
}
Note:
Cette fonction ne fonctionne pas avec les types de table non transactionnelle (comme MyISAM ou ISAM).