What are best practices for automatically deleting inactive user accounts in PHP after a certain period of time?

Automatically deleting inactive user accounts in PHP after a certain period of time helps maintain database cleanliness and security by removing unused accounts. One way to achieve this is by setting a timestamp for the last login or activity of each user and then periodically checking and deleting accounts that have been inactive for a specified duration.

// Check for inactive user accounts and delete them
$inactive_duration = 90; // 90 days of inactivity before deletion
$current_time = time();

// Query to select inactive users
$query = "SELECT id FROM users WHERE last_login < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL $inactive_duration DAY))";
$result = mysqli_query($connection, $query);

// Delete inactive users
while ($row = mysqli_fetch_assoc($result)) {
    $user_id = $row['id'];
    $delete_query = "DELETE FROM users WHERE id = $user_id";
    mysqli_query($connection, $delete_query);
}