Delete item from the table if it's date is passed [duplicate] - php

This question already has answers here:
MYSQL Select rows where date is older than datetime
(3 answers)
Closed 6 years ago.
Hey I have a table that every row contains several data and one of them is the date , I am trying to write a code in php that will run on the table and delete every row that its date have been expired for example if the date today is 06/01/2017 than every item that its date is smaller than today should be deleted, the thing is I don't really have an idea on how to write this function so if someone can send me a tutorial or example of how should I do it that will be great.

DELETE FROM your_table WHERE your_date_column < NOW() for what concerns the SQL query... Then simply use PDO to execute it
Your question actually is quite general, sounds like homework... Otherwise, posting some code attempts is appreciated as much as showing you did try / make some research beforehand. :)

You'll need to create a page that sets tomorrow's date and executes the mysql command:
$conn = new mysqli($db_servername, $db_username, $db_password, $db_dbname);
if ($conn->connect_error) { }
$tomorrow = new DateTime('tomorrow');
$tomorrow->format('Y-m-d');
$sql = "DELETE FROM 'yourtable' WHERE Date < '{$tomorrow}'";
$result = $conn->query($sql);

you can use this query for delete past records
mysql> delete from your_table where date < curdate();

Related

Insert into select only inserts one row on initial run but is fine each time afterwards

basically I am using php and mysql to extend the functionality of a mailing client, data is sent over to my server using curl and then inputted into table A in my database, I then select all of the data from table A when it matches today's date and insert it into table B if the dates match like so:
$date = $_POST['dateAdded'];
$today = date("Y-m-d");
if ($date === $today) {
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql="INSERT INTO `$tableB` (`$fields`) SELECT * FROM $tableA WHERE date_Added='$today'";
$link->exec($sql);
There is other code that is ran within this IF statement but I do not feel it is relevant to the question. I know there are other issues with this code such as not escaping post values etc but that is something I am going to tackle in the near future. The problem is that whenever this code is run as part of a cron job it only inserts one row into $tableB but when I clear tableB and one value matching $today from tableA and re-run the code it works everytime (i.e. if I run it manually), the only time it doesn't work is through the cron job. If there is any more code that is needed I am happy to provide it and any help is welcome.
The cron job is run using curl as the data is on a different server.
Could this be to do with the way curl is sending data initially through the cron?
Or is it a problem with the SQL statement itself?
Thanks.
be carefull, is de date_Added a date field or timestamp? in MySQL, is not the same, because your date("Y-m-d") against a timestamp is gonna be messed up and problably there lies your problem
try to change
$today = date("Y-m-d")
TO
$today = date("Y-m-d H:i:s");
with the info you give it's the only thing that comes to mind
The problem with this statement did lie with the way I was using $today but not in the way described above. The problem was solved with a change to the MySQL statement that inserts the data into the database:
This:
$sql="INSERT INTO$tableB($fields) SELECT * FROM $tableA WHERE date_Added='$today'";
Needed to be changed to this:
$sql="INSERT INTO$tableB($fields) SELECT * FROM $table WHERE date_Added between '$date_24_hours' AND '$today'";
Where $date_24_hours is this: $date_24_hours = date('Y-m-d', strtotime($today . ' -1 day'));
There is a need for a comparison between the two dates here otherwise the cron job gets confused with itself and feels it has completed after the first insert completes. Just thought I would share the knowledge since my problem has been solved.

Show all results from database where mm/dd/yy date is "today" or greater

I am using HTML input type="date" to allow users to input appointment dates.
Now I want to query the database and show all appointments that are "today" and in the future.
Not dates that have already passed.
Here is my SQL Script
$today = date('d-m-Y');
$sql = "SELECT *
FROM `client1`
WHERE `client` = '$customer'
AND DATEDIFF('$today', `date`) >= 0
ORDER BY `id` DESC";
Can someone guide me as to how I can achieve this?
I have seen several directions online but I want to have the sorting done at the moment of query.
I have solved the issue!
My date() format was incorrect because HTML input type="date" inserts YYYY-MM-DD into the database =/
$today = date('d-m-Y');
should be
$today = date('Y-m-d');
My operator >= should have been <= to show today and future dates.
Thanks everyone for the help. I should have tried fixing it for 5 more minutes before posting.
Why are you using PHP to compare dates in the database? I assume its a date field so you can use MySQL to do it for you:
SELECT *
FROM `client1`
WHERE `client` = '$customer'
AND DATEDIFF(date_format(now(), '%Y/%m/%d'), `date`) >= 0
ORDER BY `id` DESC
None of the responses have specified sargable predicates. If you perform an operation on a column in the where clause, there is no discernible stopping point.
where ... some_function( some_field ) = some_constant_value ...
Even if some_field is indexed, a complete table scan must be performed because there is no way to know if the output of the operation is also ordered.
From my understanding the date column is in a sortable form -- either a date field or a string in lexically sortable format 'yyyy-mm-dd'. That being the case, don't do any operation on it.
where ... some_field >= now() ...
Thus the system can use the result of now() as a target value to find exactly where in the index to start looking. It knows it can ignore all the rows with indexed values "down" from the target value. It has to look only at rows with indexed values at or "up" from the target value. That is, it performs an index seek to the correct starting point and proceeds from there. This could mean totally bypassing many, many rows.
Or, to put it bluntly, ditch the datediff and do a direct comparison.

MySQL selecting rows where datetime is X days ago [duplicate]

This question already has answers here:
Add 2 hours to current time in MySQL?
(5 answers)
Closed 9 years ago.
I have a table in database for meeting schedules. It has 2 columns named start and end and since I dont have access to the php script which fills this table with new data, I am not sure in which format it is.
But PHPMyAdmin shows taht the columns for start and end are varchar(15) So I guess it should be datetime compatible.
Example in DB: 1378033200
Which shows as 01 September 2013
My question is, I want to pull the meetings and show them in a html page, but I do not want meetings which are older than 2 days ago (server time) to show up. What will be the query?
SELECT * FROM schedules ORDER BY start
Something like
SELECT * FROM schedules ORDER BY start WHERE start > 2 days ago
I tried this but it seems it does nothing!
SELECT *
FROM schedules
WHERE COALESCE(start, 0) < CURDATE() - INTERVAL 2 DAY
ORDER BY start
But PHPMyAdmin shows taht the columns for start and end are
varchar(15) So I guess it should be datetime compatible.
You've guessed wrong. Strings are only sortable as strings. Which means, unless you're using a sortable date formats (YYYY/MM/DD being one: I'm not aware of others) you'll have to parse all the results and do the calculation by yourself in PHP (otherwise, 13/11/2000 will come before 14/01/2000). Alternatively, you might wanna use the proper type for your column: datetime, date or timestamp. Once you'll do that, you'll be able to query your db and compare dates with < and > operators.
For the 2 days ago part, you'd like to know that MySql has a built in NOW variable to which you can sum/subtract days. If you'll design your db correctly, you won't even have to touch PHP (which a desiderable thing).
Try this:
SELECT *
FROM schedules
WHERE COALESCE(start, 0) < DATE_SUB(NOW(), INTERVAL 2 DAYS)
ORDER BY start

How do I make now() be yesterday [duplicate]

This question already has answers here:
MySQL selecting yesterday's date
(8 answers)
Closed 9 years ago.
I want to set dealend to be Yesterday instead of now. Is there a way to do it in this command line?
$query = mysqli_query($myConnection, "UPDATE bookdeals SET dealend='now()' WHERE id='$pid'") or die (mysqli_error($myConnection));
... SET dealend = now() - INTERVAL 1 DAY
Note that with the 'now()' you're using, you're not using a function called "now". You're trying to set your table field to be a string whose contents are the letters n, o, w etc.... Quotes turn things into strings and those things lose their specialty once they've been stringed.
now() is a SQL function that is determined by the starting time of the transaction. You can changed the value of it by calling
SET TIMESTAMP = ...
However, for this to work it would need to be in the same transaction as your UPDATE query. What I would recommend instead is doing something like:
UPDATE bookdeals SET dealend=DATE_SUB(NOW(), INTERVAL 1 DAYS) WHERE id='$pid'
This uses the MySQL SUB_DATE() function, which will subtract one day from the current time.
You could use the MySQL DATE_SUB function
... dealend=DATE_SUB(now(),INTERVAL 1 DAY) ...
Read here for more information about MySQL date function

A not working mysql delete query. Why?

I have a table with 3 rows and one of those contains a unique time code (ex: 1308162911). There are a lot of these records but I want to delete all records which are bigger than one day (AKA 86400 seconds). I have this query but it doesn't work (nothing happens):
$db = mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database,$db)or die( "Unable to select database");
$now = time() - 86400;
$delete = ("DELETE FROM $tbl WHERE time > '$now'");
I'm not sure about MySQL, but probably you need something like that:
DELETE FROM $tbl WHERE DATEDIFF('$now', time) > INTERVAL 1 DAY
How about something like this:
$yesterday = strtotime('-1 day');
$delete = "DELETE FROM $tbl WHERE time > FROM_UNIXTIME($yesterday)";
The above query will delete all rows where the "time" value is greater than exactly 24 hours ago. This assumes that the "time" field is a TIMESTAMP, DATETIME or DATE type. If you want to delete records that are older than a day, change the > for a <.
select * from table
where now() - interval 1 day > from_unixtime(unix_timestamp_field)
if this is what you're lookin for convert the select into a delete query
This should work:
DELETE FROM $tbl
WHERE FROM_UNIXTIME(`time`) > DATE_SUB(NOW(), INTERVAL 1 DAY);
Or otherwise, in your code, I think you should remove the single-quotes around $now. However, I think it is a good idea to do it all as part of a MySQL query to avoid any time differences between PHP and MySQL if they are both running in different time-zones
Unix timestamp increases as time goes on so your query will delete all records more recent than 24 hours ago, not longer than 24 hours ago.
You should be OK to remove the single quotes around the timestamp value too.
If you're still having a problem please can you include the line of code that executes mysql_query() and the format of the database (output of SHOW CREATE TABLE myTable)

Categories