在php中删除1周后的日期

Been a long while since I posted here, I have done a LOT of coding without having to ask but I am stuck :(

I have a variable which is called "$date", it is always the current date. Now I have logs which have a date set to them, now what I want to do is delete any logs that are older than a week from the current date. Here's how I'm doing it (? means I don't know what to put).

$date = date('Y-m-d H:i:s');

$one_week_old = $date - ?;

$clearlog = mysqli_query($con,"DELETE FROM logs WHERE logs.date < '$one_week_old'");

You can do this:

$one_week_old = date("Y-m-d",strtotime("-1 week"));

$one_week_old = date('d-m-Y', strtotime("-1 week"));

Instead of using another variable, you can just query it directly:

$clearlog = mysqli_query($con,"DELETE FROM logs WHERE logs.date < dateadd(week,-1,getdate()));

If you don't need this date information later in PHP, i suggest you to do that directly in the MySql Query. Please consider, that this example will modify just the datepart, not the timepart of the current timestamp. It was't specified exactly if you like to to have whole days deleted or exactly the those data older then 604800 seconds (7 x 24 x 60 x 60 = 604800).

MySQL 5.5 Reference Manual 12.7 Date and Time Functions

mysqli_query($con, "DELETE FROM logs WHERE logs.date < DATE_SUB(NOW(), INTERVAL 1 WEEK)");
$date = date('Y-m-d');
$newdate = strtotime ( '-1 week' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-d' , $newdate );
$query="DELETE FROM logs WHERE logs.date < '".$newdate." 00:00:00 '";
$clearlog = mysqli_query($con,$query);

If you prefer Oriented Object paradigm, we have:

$oneWeekAgo = (new DateTime('-1 week'))->format('d/m/Y');

Explanation:

  • Return a new DateTimeObject
  • Set the timestamp from -1 week
  • Format to your need.