How can PHP be used to automatically delete records in a MySQL database based on a specified date criteria?
To automatically delete records in a MySQL database based on a specified date criteria, you can use PHP to write a script that connects to the database, queries the records that meet the specified date criteria, and then deletes those records.
<?php
// Connect to MySQL 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);
}
// Specify the date criteria for deletion
$date_criteria = "2022-01-01";
// Query and delete records based on the date criteria
$sql = "DELETE FROM table_name WHERE date_column < '$date_criteria'";
if ($conn->query($sql) === TRUE) {
echo "Records deleted successfully based on the specified date criteria";
} else {
echo "Error deleting records: " . $conn->error;
}
// Close the database connection
$conn->close();
?>
Keywords
Related Questions
- What are common challenges with transferring JPG files to a server using PHP?
- What are the best practices for handling date fields in PHP when inserting data into a database?
- Are there any potential pitfalls when manipulating array entries in PHP, especially when the array structure needs to be modified for a specific function?