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 get the version of MySQL using PHP?
- How to update to null value in MySQL using PHP?
- How to use a MySQL union in PHP?
- How to create an SSL connection to MySQL using PHP?
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to check the result of an insert in PHP and MySQL?
- How to escape a string for MySQL in PHP?
- How to change database in MySQL with PHP?
- How to generate a UUID in MySQL using PHP?
- How to set a timeout for MySQL query in PHP?
See more codes...