Current Location: Home> Function Categories> mysqli::rollback

mysqli::rollback

(mysqli_rollback) Rollback the current transaction
Name:mysqli::rollback
Category:MySQLi
Programming Language:php
One-line Description:Roll back the current transaction of the database.

Definition and usage

rollback() / mysqli_rollback() function rolls back the current transaction of the specified database connection.

Tip: You can also view the commit() function, which commits the current transaction; and the autocommit() function, which enables or turns off the automatic submission of database modifications.

Example

Example 1 - Object-Oriented Style

Turn off automatic commit, execute some queries, submit the query, and then roll back the current transaction:

 <?php
$mysqli = new mysqli ( "localhost" , "my_user" , "my_password" , "my_db" ) ;

if ( $mysqli -> connect_errno ) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error ;
  exit ( ) ;
}

// Turn off automatic submission
$mysqli -> autocommit ( FALSE ) ;

// Insert some values
$mysqli -> query ( "INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Peter','Griffin',35)" ) ;
$mysqli -> query ( "INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)" ) ;

// Submit transaction
if ( ! $mysqli -> commit ( ) ) {
  echo "Commit transaction failed" ;
  exit ( ) ;
}

// Roll back the transaction
$mysqli -> rollback ( ) ;

$mysqli -> close ( ) ;
?>

Example 2 - Procedural Style

Turn off automatic commit, execute some queries, submit the query, and then roll back the current transaction:

 <?php
$con = mysqli_connect ( "localhost" , "my_user" , "my_password" , "my_db" ) ;

if ( mysqli_connect_errno ( ) ) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error ( ) ;
  exit ;
}

// Turn off automatic submission
mysqli_autocommit ( $con , FALSE ) ;

// Insert some values
mysqli_query ( $con , "INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Peter','Griffin',35)" ) ;
mysqli_query ( $con , "INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)" ) ;

// Submit transaction
if ( ! mysqli_commit ( $con ) ) {
  echo "Commit transaction failed" ;
  exit ( ) ;
}

// Roll back the transaction
mysqli_rollback ( $con ) ;

// Close the connection
mysqli_close ( $con ) ;
?>
Similar Functions
Popular Articles