php-mysqlHow to use MySQL transactions in PHP?
MySQL transactions are used to ensure data integrity and atomicity when performing multiple operations on a database. Transactions are started with the begin
statement and committed with the commit
statement.
Example code
<?php
$conn = new mysqli("localhost", "user", "password", "database");
// Start transaction
$conn->begin_transaction();
// Perform queries
$conn->query("INSERT INTO table (column1, column2) VALUES (value1, value2)");
$conn->query("UPDATE table SET column1 = value1 WHERE column2 = value2");
// Commit transaction
$conn->commit();
$conn->close();
?>
Output example
No output
Code explanation
$conn = new mysqli("localhost", "user", "password", "database");
- Establishes a connection to the MySQL database.$conn->begin_transaction();
- Starts a transaction.$conn->query("INSERT INTO table (column1, column2) VALUES (value1, value2)");
- Inserts a row into the table.$conn->query("UPDATE table SET column1 = value1 WHERE column2 = value2");
- Updates a row in the table.$conn->commit();
- Commits the transaction.$conn->close();
- Closes the connection to the MySQL database.
Helpful links
More of Php Mysql
- How to join tables with PHP and MySQL?
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to check the result of an insert in PHP and MySQL?
- How to create an SSL connection to MySQL using PHP?
- How to check if a record exists in PHP and MySQL?
- How to get the last insert ID in PHP MySQL?
- How to use a variable in a MySQL query using PHP?
- How to fetch data from MySQL in PHP?
- How to convert MySQL datetime to string in PHP?
- How to use a MySQL union in PHP?
See more codes...