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 use a variable in a MySQL query using PHP?
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to get the first row of a result in MySQL using PHP?
- How to get the last insert ID in PHP MySQL?
- How to convert MySQL datetime to string in PHP?
- How to update to null value in MySQL using PHP?
- How to write an update query in MySQL using PHP?
- How to use a MySQL union in PHP?
- How to set a timeout for MySQL query in PHP?
- How to export data from MySQL to Excel using PHP?
See more codes...