How can the provided PHP script be optimized to efficiently delete database entries that are past a certain date?

The provided PHP script can be optimized by using a SQL query to efficiently delete database entries that are past a certain date. By using a DELETE query with a WHERE clause that filters entries based on their date, we can target and remove only the records that meet the specified criteria. This approach reduces the need for iterating through each record individually, resulting in a more streamlined and efficient deletion process.

<?php
// Establish a database connection
$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 date threshold
$dateThreshold = '2022-01-01';

// Delete entries past the specified date
$sql = "DELETE FROM your_table_name WHERE date_column < '$dateThreshold'";

if ($conn->query($sql) === TRUE) {
    echo "Records deleted successfully";
} else {
    echo "Error deleting records: " . $conn->error;
}

// Close the database connection
$conn->close();
?>