Transactions in MySQL are used to ensure data integrity and handling multiple operations as a single unit. A transaction can be committed if all operations are successful or rolled back if any operation fails. Here’s how you can implement transactions in MySQL using PHP:
<?php
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Start transaction
$mysqli->begin_transaction();
try {
// Execute the first query
$mysqli->query("INSERT INTO users (username, email) VALUES ('user1', 'user1@example.com')");
// Execute the second query
$mysqli->query("INSERT INTO orders (user_id, product_id) VALUES (1, 2)");
// Commit transaction
$mysqli->commit();
echo "Transaction completed successfully.";
} catch (Exception $e) {
// Rollback transaction on error
$mysqli->rollback();
echo "Transaction failed: " . $e->getMessage();
}
// Close connection
$mysqli->close();
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?