commit() in PHP Example



The commit() / mysqli_commit() function commits the current transaction for the specified database connection.

PHP MySQL commit() Example

<?php
$host= "localhost";
$username= "root";
$password = "";

$db_name = "demo_db";

$mysqli = mysqli_connect($host, $username, $password, $db_name);
 
// Check connection
if ($mysqli->connect_errno) {
    printf("connection failed: %s\n", $mysql_connection->connect_error());
    exit();
}

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

// Insert some values
$mysqli -> query("INSERT INTO Students (FirstName,LastName,Age)
VALUES ('Tony','stark',35)");
$mysqli -> query("INSERT INTO Students (FirstName,LastName,Age)
VALUES ('Ram','Jadhav',33)");

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

$mysqli -> close();
?>
Let's understand the above PHP script.

The mysqli_connect() function opens a new connection to the MySQL server:

$host= "localhost";
$username= "root";
$password = "";

$db_name = "demo_db";

$mysqli = mysqli_connect($host, $username, $password, $db_name);
Turn off auto-commit:
// Turn autocommit off
$mysqli -> autocommit(FALSE);
SQL insert queries:
// Insert some values
$mysqli -> query("INSERT INTO Students (FirstName,LastName,Age)
VALUES ('Tony','stark',35)");
$mysqli -> query("INSERT INTO Students (FirstName,LastName,Age)
VALUES ('Ram','Jadhav',33)");
Commit the transaction:
// Commit transaction
if (!$mysqli -> commit()) {
  echo "Commit transaction failed";
  exit();
}
Close connection:
$mysqli -> close();

Comments