Using Transactions in MySQLi : mysqli_autocommit « MySQL Database « PHP






Using Transactions in MySQLi

 
<?php

    $mysqli = new mysqli("localhost", "username", "password",
                         "mydatabase", 3306);

    $query = "CREATE TEMPORARY TABLE friends (name VARCHAR(50), age INT) TYPE=InnoDb";

    mysqli_query($mysqli, $query);

    mysqli_autocommit($mysqli, false);

    $friends = array(
                    array("name" => "Max",
                          "age" => 22),
                    array("name" => "Cliff",
                          "age" => 45),
                    array("name" => "Hollie",
                          "age" => 18));

    foreach($friends as $friend) {
        $query = "INSERT INTO friends VALUES('{$friend['name']}',{$friend['age']})";
        mysqli_query($mysqli, $query);
    }
    mysqli_commit($mysqli);

    $result = mysqli_query($mysqli, "SELECT COUNT(*) FROM friends");
    $rows = mysqli_num_rows($result);

    mysqli_rollback($mysqli);

    $result = mysqli_query($mysqli, "SELECT COUNT(*) FROM friends");
    $rows = mysqli_num_rows($result);

    echo "There are $rows rows(s) in the table (after rollback)<BR/>\n";

    mysqli_close($mysqli);

?>
  
  








Related examples in the same category