How can a PHP script be set up to delete a database record after a certain amount of time?
To delete a database record after a certain amount of time, you can use a timestamp field in your database to store the time when the record was created. Then, in your PHP script, you can compare the current time with the timestamp to determine if the record should be deleted.
// Connect to the 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);
}
// Query to select records older than a certain time (e.g. 24 hours)
$sql = "DELETE FROM your_table WHERE TIMESTAMPDIFF(HOUR, created_at, NOW()) > 24";
if ($conn->query($sql) === TRUE) {
echo "Records deleted successfully";
} else {
echo "Error deleting records: " . $conn->error;
}
// Close the connection
$conn->close();
Keywords
Related Questions
- What alternative approach is suggested in the forum thread for passing field names to the function?
- What are some recommended resources or tutorials for beginners looking to improve their PHP skills for database interactions like user logins?
- Are there any potential errors in the way the date and time data is being retrieved and formatted in the PHP script?