What are the advantages of storing data atomically in a database instead of using serialization?

Storing data atomically in a database ensures that all related data is either saved or not saved together as a single unit, preventing inconsistencies or partial updates. This is especially important in situations where multiple operations need to be executed together to maintain data integrity. Using serialization, on the other hand, can lead to issues such as data corruption or outdated information if the serialization process is interrupted midway.

// Example of storing data atomically in a database using transactions in PHP

// Start a transaction
$pdo->beginTransaction();

try {
    // Perform multiple database operations
    $pdo->query("INSERT INTO table1 (column1) VALUES ('value1')");
    $pdo->query("UPDATE table2 SET column2 = 'new_value' WHERE id = 1");
    
    // Commit the transaction if all operations succeed
    $pdo->commit();
} catch (Exception $e) {
    // Rollback the transaction if any operation fails
    $pdo->rollback();
    echo "Transaction failed: " . $e->getMessage();
}