What best practice should be followed when deleting database entries based on date comparison in PHP?
When deleting database entries based on date comparison in PHP, it is best practice to use prepared statements to prevent SQL injection attacks. Additionally, it is important to properly format the date comparison in the SQL query to ensure accurate results.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare the SQL query to delete entries older than a specific date
$date = date('Y-m-d', strtotime('-30 days'));
$stmt = $pdo->prepare("DELETE FROM mytable WHERE date_column < :date");
// Bind the date parameter and execute the query
$stmt->bindParam(':date', $date);
$stmt->execute();
Keywords
Related Questions
- How can PHP be used to check if a value in a MySQL table matches another value in the same table?
- How can PHP be used to automatically delete specific entries from a text file after they have been used?
- How does the order of function calls and returns impact the execution of nested functions in PHP?