• PHP Video Tutorials

PHP mysqli_begin_transaction() Function



Definition and Usage

The mysqli_begin_transaction() is used to start a new transaction.

Syntax

mysqli_begin_transaction($con, [$flags, $name]);

Parameters

Sr.No Parameter & Description
1

con(Mandatory)

This is an object representing a connection to MySQL Server.

2

flags(Optional)

A constant which can be on of the following :

  • MYSQLI_TRANS_START_READ_ONLY

  • MYSQLI_TRANS_START_READ_WRITE

  • MYSQLI_TRANS_START_WITH_CONSISTENT_SNAPSHOT

3

name(Optional)

This is string value representing the name of the save point of the transaction.

Return Values

The PHP mysqli_begin_transaction() function returns a boolean value which is, true if the operation is successful and, false if not.

PHP Version

This function was first introduced in PHP Version 5 and works in all the later versions.

Example

Following example demonstrates the usage of the mysqli_begin_transaction() function (in procedural style) −

<?php
   //Creating a connection
   $con = mysqli_connect("localhost", "root", "password", "mydb");

   //Beginning the transaction
   mysqli_begin_transaction($con, MYSQLI_TRANS_START_READ_ONLY);
   print("Transaction Started......\n");

   //Creating a table
   mysqli_query($con, "CREATE TABLE Test(Name VARCHAR(255), AGE INT)");
   print("Table Created......\n");

   //Inserting values
   mysqli_query($con, "INSERT INTO Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)");
   print("Records Inserted......\n");

   //Committing the transaction
   mysqli_commit($con);
   print("Transaction Saved......\n");

   //Closing the connection
   mysqli_close($con);
?>

This will produce following result −

Transaction Started......
Table Created......
Records Inserted......
Transaction Saved......

Example

The syntax of this method in object oriented style is $con->begin_transaction(). Following is an example of this function in object oriented mode $minus;

//Creating a connection
$con = new mysqli("localhost", "root", "password", "mydb");

//Beginning the transaction
$con->begin_transaction($con, MYSQLI_TRANS_START_READ_ONLY);
print("Transaction Started......\n");

//Creating a table
$con->query("CREATE TABLE Test(Name VARCHAR(255), AGE INT)");
print("Table Created......\n");

//Inserting values
$con->query("insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)");
print("Records Inserted......\n");

//Committing the transaction
$con->commit();
print("Transaction Saved......\n");

//Closing the connection
$con->close();
?>

This will produce following result −

Transaction Started......
Table Created......
Records Inserted......
Transaction Saved......
php_function_reference.htm
Advertisements