What is the recommended method for automatically deleting database records after a certain period of time in PHP?

To automatically delete database records after a certain period of time in PHP, you can use a cron job to run a PHP script at set intervals. Within the PHP script, you can query the database for records that are older than the specified time period and delete them accordingly.

<?php
// Connect to your database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Define the time period for deletion (e.g. 30 days)
$deletePeriod = strtotime('-30 days');

// Delete records older than the defined time period
$sql = "DELETE FROM your_table WHERE timestamp_column < $deletePeriod";
if ($conn->query($sql) === TRUE) {
    echo "Records deleted successfully";
} else {
    echo "Error deleting records: " . $conn->error;
}

$conn->close();
?>