Laracon EU Online 2021

mysqli::begin_transaction

mysqli_begin_transaction

(PHP 5 >= 5.5.0, PHP 7)

mysqli::begin_transaction -- mysqli_begin_transactionDémarre une transaction

Description

Style orienté objet

public mysqli::begin_transaction ([ int $flags = 0 [, string $name ]] ) : bool

Style procédural:

mysqli_begin_transaction ( mysqli $link [, int $flags = 0 [, string $name ]] ) : bool

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.

Liste de paramètres

link

Seulement en style procédural : Un identifiant de lien retourné par la fonction mysqli_connect() ou par la fonction 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.

Valeurs de retour

Cette fonction retourne TRUE en cas de succès ou FALSE si une erreur survient.

Notes

Note:

Cette fonction ne fonctionne pas avec les types de table non transactionnelle (comme MyISAM ou ISAM).

Exemples

Exemple #1 Exemple avec mysqli::begin_transaction()

Style orienté objet

<?php

/* Demande à mysqli de lancer une exception si une erreur survient */
mysqli_report(MYSQLI_REPORT_ERROR MYSQLI_REPORT_STRICT);

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

/* Le moteur de table supporte les transactions */
$mysqli->query("CREATE TABLE IF NOT EXISTS language (
    Code text NOT NULL,
    Speakers int(11) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"
);

/* Démarre la transaction */
$mysqli->begin_transaction();

try {
    
/* Insère plusieurs valeurs */
    
$mysqli->query("INSERT INTO language(Code, Speakers) VALUES ('DE', 42000123)");

    
/* Tente d'insérer de mauvaises valeurs */
    
$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();

    
/* Si le code arrive à ce point sans erreur, alors on commit les données dans
       la base de données */
    
$mysqli->commit();
} catch (
mysqli_sql_exception $exception) {
    
$mysqli->rollback();

    throw 
$exception;
}

Style procédural

<?php

/* Demande à mysqli de lancer une exception si une erreur survient */
mysqli_report(MYSQLI_REPORT_ERROR MYSQLI_REPORT_STRICT);

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

/* Le moteur de table supporte les transactions */
mysqli_query($mysqli"CREATE TABLE IF NOT EXISTS language (
    Code text NOT NULL,
    Speakers int(11) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"
);

/* Commence la transaction */
mysqli_begin_transaction($mysqli);

try {
    
/* Insère plusieurs valeurs */
    
mysqli_query($mysqli"INSERT INTO language(Code, Speakers) VALUES ('DE', 42000123)");

    
/* Tente d'insérer de mauvaises valeurs */
    
$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);

    
/* Si le code arrive à ce point sans erreur, alors on commit les données dans
       la base de données */
    
mysqli_commit($mysqli);
} catch (
mysqli_sql_exception $exception) {
    
mysqli_rollback($mysqli);

    throw 
$exception;
}

Voir aussi

add a note add a note

User Contributed Notes 4 notes

up
5
Ral
2 years ago
If you receive errors like: "This server version doesn't support 'READ WRITE' and 'READ ONLY'. Minimum 5.6.5 is required" with versions of MariaDB that DO support them, this is due to an internal check in mysqli conflicting with a hack in MariaDB to allow replication with oracle mysql.

MariaDB prefixes its server version numbers with "5.5.5-" for example "5.5.5-10.3.7-MariaDB-1:10.3.7+maria~stretch". This is because oracle mysql would interpet the "10" as version 1. Mysql clients aware of MariaDB have been updated to detect and strip this prefix.

However the check for mysqli.begin-transaction sees the 5.5.5 prefix and so fails.

The workaround is to specify a custom version string without the prefix for MariaDB on the command line using the --version option. Then mysqli.begin-transaction functions as expected.
up
1
PHP Guru
7 months ago
MySQL 5.6 introduces READ ONLY mode which applies optimizations to your transactions that can only be applied when it knows in advance that no table modifications will be made and that no locks will be issued.

The default access mode is READ WRITE in all versions up to and including MySQL 5.6. Starting in MySQL 5.7, the appropriate access mode is detected automatically. So if your transaction attempts modifications or table locks, it will automatically use READ WRITE mode, otherwise it will use READ ONLY mode and your transaction will benefit from the optimizations that come from that without having to explicitly declare is as READ ONLY.

Therefore the only time you need to explicitly declare an access mode is when you are using MySQL 5.6 and you are sure that you want READ ONLY mode. Note that any queries that attempt to modify tables or issue locks in READ ONLY mode will fail. Temporary tables can still be modified.

(Moderators. This post should replace the previous post that I made on the subject. Thanks.)
up
1
VasK@hapir
1 year ago
The above answer from Ral worked for us, Thanks a lot. This is how we implemented the proposed workaround for

Warning: mysqli_begin_transaction(): This server version doesn't support 'READ WRITE' and 'READ ONLY'. Minimum 5.6.5 is required

We appended the following line to /etc/my.cnf and restarted MySQL server

version=10.2.19-MariaDB
up
-1
Luc
4 years ago
For PHP<5.5:

    mysqli_query($db, "START TRANSACTION");
To Top