Skip to content
PHP Logo

Are there any specific PHP functions or methods that can simplify the process of deleting old entries from a database?

When deleting old entries from a database, one approach is to use the PHP function `strtotime()` to calculate the timestamp for the cutoff date. This timestamp can then be used in a SQL query to delete entries older than the cutoff date. By utilizing this method, the process of deleting old entries can be simplified and automated.

php
// Calculate the timestamp for the cutoff date (e.g. 30 days ago)
$cutoff_date = strtotime('-30 days');

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');

// Prepare and execute a SQL query to delete entries older than the cutoff date
$stmt = $pdo->prepare("DELETE FROM my_table WHERE entry_date < :cutoff_date");
$stmt->bindParam(':cutoff_date', $cutoff_date, PDO::PARAM_INT);
$stmt->execute();