Commit and Rollback in PHP MySQL


Normally, MySQL make permanent all changes in current transactions. We can turn-off autocommit (autocommit(FALSE)) and use rollback() to erase all changes in current transaction. And use commit() to make Permanent all changes in current transaction.This example shows, how to use commit() and rollback() in PHP.

Example:

<?php
  //database connection
  $con=mysqli_connect('localhost','root','','db_sample');
  
  //disable MySQL autocommit 
  $con->autocommit(FALSE);
  try{
    
    $sql="insert into products(pname,price) value('Apple',25)";
    if(!$con->query($sql)){
      throw new Exception('Product Added Failed');
    }
    
    $sql="insert into products(pname,price) value('Orange',100)";
    if(!$con->query($sql)){
      throw new Exception('Product Added Failed');
    }
    
    //permanent all changes in current transaction.
    $con->commit();
  }catch(Exception $e){
    //cancel all changes in current transaction.
    $con->rollback();
    echo $e->getMessage();
  }
?>