Skip to content
PHP Logo

How can PHP developers ensure that old values are properly saved in a log when updating database records?

When updating database records, PHP developers can ensure that old values are properly saved in a log by first retrieving the current values of the record before updating it. These values can then be stored in a separate log table or file for future reference. By keeping track of the old values before making any changes, developers can maintain a record of the data history and easily identify any discrepancies or issues that may arise.

php
// Retrieve current values of the record before updating
$currentValues = $db->query("SELECT * FROM your_table WHERE id = :id", ['id' => $recordId])->fetch();

// Update the record with new values
$db->query("UPDATE your_table SET column1 = :value1, column2 = :value2 WHERE id = :id", ['value1' => $newValue1, 'value2' => $newValue2, 'id' => $recordId]);

// Save old values in a log table
$db->query("INSERT INTO log_table (record_id, old_column1, old_column2) VALUES (:recordId, :oldValue1, :oldValue2)", ['recordId' => $recordId, 'oldValue1' => $currentValues['column1'], 'oldValue2' => $currentValues['column2']);