← Back to PHP Course | Chapter 11: Database | Lesson 7 of 21

PHP Transactions

एक transaction एक all-or-nothing deal जैसा है: या तो हर step काम करता है, या कोई भी count नहीं होता। अगर एक account से दूसरे में पैसे move करना बीच में fail हो जाए, सब कुछ वापस put back हो जाता है।
Syntax
php
try {
    $pdo->beginTransaction();
    // several queries
    $pdo->commit();       // save all changes
} catch (Exception $e) {
    $pdo->rollBack();     // undo all changes
}

एक Transaction क्या है?

एक database transaction कई SQL statements को एक single all-or-nothing unit में group करता है — या तो इसमें हर statement succeed करके save हो जाता है, या अगर कोई एक fail हो, सब roll back हो जाते हैं ऐसे जैसे कोई चला ही न हो।

उदाहरण: What is a Transaction?

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE accounts (id INTEGER, balance INTEGER)");
$db->exec("INSERT INTO accounts VALUES (1, 100), (2, 50)");
// Print "All statements in a transaction succeed together, or none do" to the output
echo "All statements in a transaction succeed together, or none do";
?>

Changes को Commit करना

beginTransaction() (PDO) या mysqli का begin_transaction() एक transaction की शुरुआत mark करता है, जिसके बाद बाद की queries तुरंत permanently committed होने के बजाय एक pending state में रखी जाती हैं।

उदाहरण: Committing Changes

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE accounts (id INTEGER, balance INTEGER)");
$db->exec('BEGIN');
$db->exec("INSERT INTO accounts VALUES (1, 100)");
// Print "Insert is pending, not yet committed" to the output
echo "Insert is pending, not yet committed";
?>

Changes को Rollback करना

commit() transaction शुरू होने के बाद किए गए हर change को permanently save करता है, जबकि rollback() उन्हें सब discard कर देता है — एक catch block के अंदर rollback() call करना बीच में एक failed step पर react करने का standard pattern है।

उदाहरण: Rolling Back Changes

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE accounts (id INTEGER, balance INTEGER)");
$db->exec('BEGIN');
$db->exec("INSERT INTO accounts VALUES (1, 100)");
$db->exec('ROLLBACK');
// Declare `$result`, set to `$db->query("SELECT COUNT(*) as c FROM accounts")`
$result = $db->query("SELECT COUNT(*) as c FROM accounts");
// Print a human-readable dump of `$result->fetchArray()`
print_r($result->fetchArray());
?>

Savepoints के साथ Transactions

Transactions सबसे ज़्यादा मायने रखते हैं जब कई related writes को साथ succeed या fail करना ज़रूरी हो, जैसे दो accounts के बीच पैसे transfer करना — आप कभी नहीं चाहते कि debit succeed हो जबकि matching credit चुपचाप fail हो जाए।

उदाहरण: Transactions with Savepoints

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE accounts (id INTEGER, balance INTEGER)");
$db->exec('BEGIN');
$db->exec("UPDATE accounts SET balance = balance - 50 WHERE id = 1");
$db->exec("UPDATE accounts SET balance = balance + 50 WHERE id = 2");
$db->exec('COMMIT');
// Print "Debit and credit committed together" to the output
echo "Debit and credit committed together";
?>

MySQLi में Transactions

database operations को एक transaction के साथ try/catch में wrap करना ensure करता है कि किसी multi-step operation के बीच में एक unexpected exception database को एक half-finished state के बजाय अपनी original, consistent state में छोड़े।

उदाहरण: Transactions in MySQLi

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE accounts (id INTEGER, balance INTEGER)");
// Try running this block; jump to `catch` if it throws
try {
    $db->exec('BEGIN');
    $db->exec("UPDATE accounts SET balance = balance - 50 WHERE id = 1");
    $db->exec('COMMIT');
// Catch Exception $e
} catch (Exception $e) {
    $db->exec('ROLLBACK');
    // Print "Rolled back on failure" to the output
    echo "Rolled back on failure";
}
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. commit() call करना भूल जाना, ताकि connection बंद होते ही changes roll back हो जाएँ।
  2. एक failure के बाद catch block में rollBack() call न करना, transaction को खुला छोड़ते हुए।
  3. MyISAM जैसा एक table engine इस्तेमाल करना जो transactions support नहीं करता, ताकि rollback का कोई effect न हो।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.