Reputation: 101
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'");
Upvotes: 0
Views: 1857
Reputation: 361
If you prefer Oriented Object paradigm, we have:
$oneWeekAgo = (new DateTime('-1 week'))->format('d/m/Y');
Explanation:
Upvotes: 0
Reputation: 11
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)");
Upvotes: 1
Reputation: 11
$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);
Upvotes: 1
Reputation: 3358
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()));
Upvotes: 2
Reputation: 15609
You can do this:
$one_week_old = date("Y-m-d",strtotime("-1 week"));
Upvotes: 1