Skip to content
PHP Logo

How can PHP developers ensure data integrity when modifying database tables?

To ensure data integrity when modifying database tables, PHP developers can use transactions. By wrapping database operations in a transaction, developers can ensure that either all changes are committed or none of them are, preventing partial updates that could lead to data inconsistencies.

php
<?php

// Establish database connection
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');

// Begin transaction
$pdo->beginTransaction();

try {
    // Perform database operations
    $pdo->exec("UPDATE table_name SET column_name = 'new_value' WHERE condition");

    // Commit transaction
    $pdo->commit();
} catch (Exception $e) {
    // Rollback transaction in case of error
    $pdo->rollBack();
    echo "Error: " . $e->getMessage();
}