How can triggers be used in PHP to automate logging of changes in a database?
Triggers in PHP can be used to automate logging of changes in a database by creating triggers on the tables that need to be monitored. These triggers can be set to execute a PHP script that logs the changes whenever an INSERT, UPDATE, or DELETE operation is performed on the table.
// Create a trigger in the database to log changes in a specific table
$sql = "CREATE TRIGGER log_changes
AFTER INSERT, UPDATE, DELETE
ON table_name
FOR EACH ROW
BEGIN
// PHP script to log the changes
$log_message = 'A change was made in table_name at '.date('Y-m-d H:i:s');
file_put_contents('log.txt', $log_message.PHP_EOL, FILE_APPEND);
END";
// Execute the SQL query to create the trigger
mysqli_query($conn, $sql);