Transaction in PHP Mysql

This is how easily you can implement tractions in mysqli and PHP.

$link = mysqli_connect('localhost','root','','test');
// Check connection
if (mysqli_connect_errno()) {
mysqli_autocommit($link, FALSE); //disable autocommit
$query="insert into tb1 (username,pwd) values('pp','sdsd')";
$queryres=mysqli_query($link, $query);
    echo "error first query";
$query2="insert into tb2 (userid,name) values($id,'Prashant Bhatt')"; //u can create some error here to check that if data inserted in first table when this query failed
$query2res=mysqli_query($link, $query2);
if($queryres && $query2res)
        mysqli_commit($link); //if both query success then only commit tansaction
        echo "success all";
        mysqli_rollback($con); //if any query fails then rollback transaction
        echo "Fail transacction";
mysqli_autocommit($link, TRUE); // enable autocommit again

Note1: Because we have disabled auto commiting of queries so if you will write more queries after this code that will also not commit because those will also be part of this transaction. So you have to reset autocommit.

Note2:  mysqli_autocommit($link, TRUE); enables autocommiting and it also commits the queries which were run in transaction. So always use mysqli_rollback($con);  also.

mysqli_autocommit($link, FALSE); // turn OFF auto
-query 1;
- query 2;
mysqli_commit($link); // process ALL queries so far
-query 3;
-query 4;
mysqli_autocommit($link, TRUE); // turn ON auto and commit query 3 and 4

All 4 will be processed.