PHP Delete MySQL Records Older Than 3 Days - php

I have the following at the top of every page so when the website is loaded by anyone PHP deletes any record in a specific database table that is older than 3 days.
$conn = getConnected("oversizeBoard");
mysqli_query($conn, "DELETE FROM postedLoads WHERE date < DATE_SUB(DATE('m-d-Y'), INTERVAL 3 DAY");
The problem is nothing is being deleted.
The data type for my date column is varchar(20) and when I insert a date into MySQL it is entered using date("m-d-Y"). The name of my date field is date. So it appears that the above query would be correct, but I have done something wrong, and I am not certain as to what since every example I've looked at has basically looked the same except they used now() instead of date() but I use a specific date format so I can't use now() in my query.
What have I done wrong?
I even tried putting it into a function:
function deleteOversizeRows() {
$conn = getConnected("oversizeBoard");
mysqli_query($conn, "DELETE FROM postedLoads WHERE date < DATE_SUB(DATE('m-d-Y'), INTERVAL 3 DAY");
}
deleteOversizeRows();

Try to provide date by calculating first and then use it in query like below
$date = date("m-d-Y", strtotime('-3 day'));
$conn = getConnected("oversizeBoard");
mysqli_query($conn, "DELETE FROM postedLoads WHERE date < '".$date."');
It might help you. If need any other solution or help, do ask here.

Use MySQL function TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2);
Function calculates difference between two dates and returns output based on the unit parameter passed .
Try this:
DELETE FROM postedLoads WHERE TIMESTAMPDIFF('DAY',date,now())<3;
For detailed info of function:http://www.w3resource.com/mysql/date-and-time-functions/mysql-timestampdiff-function.php

Related

Retrieve rows within current month, week, and day using php and mysql

I have a mysql table events with column event_date varchar(10) which takes in dates in the form 7-5-2014.
I have an object which can give me:
// displays current month (5)
$m = $time->getMonth();
echo $m;
//displays current day (1)
$d = $time->getDay();
echo $d;
// displays current year (2014)
$y = $time->getYear();
echo $y;
I am trying to figure out a way to get events within the current day, month, and year.
The php query below is wrong but it gives you and idea as to what im trying to do:
$eventsWithinDay = query("SELECT * FROM events WHERE LEFT(event_date, 2)='%s'", $d);
How can I do this correctly?
Better yet, what is the most efficient way to do this?
I can make any necessary changes to the database or php.
Thanks in advance.
You an do it in various ways. For instance:
SELECT smth FROM somewhere WHERE datefield LIKE '2014-05-%'
OR
SELECT smth FROM somewhere WHERE datefield >= $start_interval and date <= $end_interval
In the latter case you'd have your date stored in a BIGINT column and use php's time() to set its value. Then using PHP's time functions (like strtotime('-1 day')) get timestamps for dates you wish to query against. So a simple example would be:
$q = "SELECT ... WHERE datefield >= " . strtotime('-2 days') // this would search for dates from at least 2 days ago
You could also use MYSQL's built-in date-time functions, but i have no experience with those so i'm not going to advice on something i don't know myself :)

PHP querying MySQL, showing "count(*)"

I have inherited an old system at work, php 4.4 and MySQL that we run our helpdesk software from, I cannot upgrade anything until next year.
I'm struggling with something though.
I need to show the total number of calls logged between 2 and 1 hour ago. in the database, the unix timestamp for each call logged is in the column "logdatex"
in my php I have the following
$OneHourAgo = strtotime('-1 hour'); //time 1 hour ago as Unix Timestamp
$TwoHoursAgo = strtotime('-400 hour'); // time 2 hours ago
$Test = mysql_query("select count(*) from opencall where logdatex between $OneHourAgo and $TwoHoursAgo") or die(mysql_error());
Now, in MySQL Query Browser, if I put in the query but replace the variables with the actual numbers (I did an echo to get the numbers) it works fine and returns the desired number:
select count(*) from opencall where logdatex between 1326767703 and
1386764103
(the above doesn't use a 1 hour sample, more like a few years) Please can you help me get the number in to a variable, I cannot figure out how to do this.
Any help appreciated
The mysql_query does not directly return the results of the query. Rather it returns a result resource. http://www.php.net/manual/en/function.mysql-query.php
So you will need to use mysql_fetch_row to get the results.
http://www.php.net/manual/en/function.mysql-fetch-row.php
$row = mysql_fetch_row($Test);
$count = $row[0];
If you have more than one row, you would loop until the mysql_fetch_row returns false. But since you know you are only going to get one row, you can do this.
You should change your query:
select count(*) from opencall where logdatex between $TwoHoursAgo and $OneHourAgo
Because http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between says, it should be between min and max.
I'm not sure to understand you but, may be that?
$OneHourAgo = strtotime('-1 hour'); //time 1 hour ago as Unix Timestamp
$TwoHoursAgo = strtotime('-2 hour'); // time 2 hours ago
A link: http://php.net/manual/es/function.strtotime.php

mysql query find date less then another date

im trying to retrieve a set of id's that are due to expire within the next 7 days, and for the life of me cant get my query to work
$target_date = date('Y-m-d', strtotime('+7 days'));
$sql = "SELECT subscriptions.`id` FROM subscriptions WHERE date($target_date) <= expires AND cust_id =$_SESSION[uid]";
any help would be greatly appreciated
This is fine:
$target_date = date('Y-m-d', strtotime('+7 days'));
As it structures the date in the same way as MySQL [YYYY-MM-DD]
I've switched your query around and applied the DATE() function to the 'expires' field and not your $target_date as it doesn't need to. Your expires field might be in [YYYY-MM-DD HH:MM:SS] format, which might be why it's not working:
$sql = "
SELECT subscriptions.id
FROM subscriptions
WHERE DATE(expires) >= '$target_date'
AND cust_id = '$_SESSION[uid]'";
Echo out the $sql query to find out if its executing it properly and Use the or die(mysql_error()); to tell you where it's failing.
Use SQL escaping too (Either PDO or mysqli) as has been outlined in another answer.
Hope this helps.
If you create a date in a roughly MySQL compatible format, it should work without having to use the DATE function, just compare it as if it were a string.
Your code is in dire need of some proper SQL escaping that would fix this problem and likely a worryingly large number of others in your application.
The query running in PDO or mysqli would look roughly like:
$target_date = date('Y-m-d', strtotime('+7 days'));
$sql = "SELECT subscriptions.`id` FROM subscriptions WHERE ?<=expires AND cust_id=?";
You can then call the appropriate bind_param method to link in the right values to those placeholders.
You can do it with MySQL:
SELECT subscriptions.`id` FROM subscriptions WHERE date_add(curdate(),interval 7 day) <= expires AND cust_id =$_SESSION[uid]

Query for events with a date and time greater than now

all - fairly simple query question that's been hounding me: How do I query for entries with a date and time only greater than now, or when the query is run (page requested)?
I've seen some examples but they aren't good enough for me to modify. Here's my code:
$todaysDate = date("Y-m-d h:i:s");
$params = array('select'=>'*', 'limit'=>3, 'orderby'=>'t.event_StartDate ASC', 't.event_StartDate < "$todaysDate"' );
An example of the variable "t.event_StartDate" outputs "2010-12-10 22:18:42" so I assume that may be how it's saved in the database.
I suspect I'm not building the date correctly or I need to be using a time function I'm not familiar with in MySQL. Help? This is for outputting a series of events with date and time.
I think you reverse the use <, it should be >
try
SELECT ... WHERE t.event_StartDate>NOW();
/* you don't even need to set $todaysDate */
t.event_StartDate > NOW() don't will returns nothing? a date higher of now lol. I'm confused.

How to use the mysql "LIKE" syntax with a timestamp?

I want to allow my users to search the database for a row that was submitted on a certain day. The date is entered into the field in the database using the date() function which is great, but when i use the php strtotime function, of course the dates are not exactly the same.
Is there some clever mysql function that can help me with this?
I had an issue with this before.
You're best to generate a start and end date then use the BETWEEN function instead.
So something like this:
$start_date = "2009-01-01 00:00:00";
$end_date = "2009-01-01 23:59:59";
$sql = "SELECT * FROM table WHERE date BETWEEN '$start_date' AND '$end_date' AND id = 'x';
Of course you would just pull your dates from the DB using strtotime and append the time stamps - depends how you used date()
Hope this helps :)
You can use MySQL's DATE() function to extract date part of the timestamp:
select ... from table ... where DATE(date_column) = '2010-01-25';
If you have problem submitting '2010-01-25' from PHP, you can use PHP's date function with 'Y-m-d' as parameter to only get the date part.
$d = date('Y-m-d', strtotime(...));
Looking at your question closely, it seems you'll need both of those. First use PHP's date function to get only the date part and then use MySQL's date to match only those records.
PHP:
$timestamp_from_php = strtotime('December 25, 2009');
SQL:
select
`fields`
from
Table t
where
date_format('Y-m-d', t.`datetime_field`) = date_format('Y-m-d', '$timestamp_from_php')

Categories