I want to know how to delete records from a MySQL Database after 1 week
This is the code I have for inserting the record and date of when it was added
INSERT INTO moviesdone VALUES ('" . $id2 . "', NOW())
Where $id is the name of what I am insterting and wanting to delete after 1 week.
I would also like to do this automatically, which I can set up from in phpMyAdmin
So, I only need to know: How do I write the date correctly (if needed) and how do I delete the record one week later?
Run this code at regular intervals, for example once per day:
DELETE FROM moviesdone
WHERE datetimecol < NOW() - INTERVAL 7 DAY
You can use the event scheduler.
If you are using MySQL 5.1.6 or greater you can use CREATE EVENT
Something like
CREATE EVENT del_entries
ON SCHEDULE EVERY 1 DAY
DO
DELETE FROM table WHERE DATEDIFF(NOW(), creation_date) >= 7;
Related
For example, I am creating a student management system and I want to increase the student standard after every year. If student is admitted in 1st standard then next year he would be in 2nd after that 3rd and so on.. Please help!
you can use MySQL EVENT like
CREATE EVENT myevent
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 YEAR
DO
UPDATE `student` SET `standard` = `standard` + 1
WHERE some_ID_Column = value;
Set up a cron job that runs nightly and run a stored procedure that checks if the students have reached the condition for the next standard and if they have update the records.
Im trying to avoid multiple sql inserts in a database. The idea is to wait at least 5 minutes before inserting again.
Getting time from last insert using
$query ="SELECT fecha
FROM almacen
WHERE fecha > NOW() - INTERVAL 5 MINUTE
ORDER BY id DESC LIMIT 1"
$espera=mysqli_query($conexion, $query)
if (empty($espera)) { inserting code } else { close }
But the query returns nothing when it should be returning a value. I was thinking it might be a problem since date was inserted using php date ( "j/n/Y h:i");
Should i change the time format? what should i use?
If you wanted to restrict your rows to only 1 entry per 5 minutes I would:
Create a column called insert_interval DATE and create a unique index on that column. Then just attempt your insert, setting the value of insert_interval to
whatever 5 minute interval the insert time falls under.
E.G. Normalize date to 5 minute interval.
select now() - interval (mod(minute(now()),5)) minute - interval second(now()) second;
Insert
insert into table(columns ..., insert_interval) values(
..., now() - interval mod(minute(now()),5) minute - interval second(now())
);
Only 1 row is allowed per 5 minute interval starting on the hour. So 1 row from 00:00:00 - 00:04:59, and so on. Any attempt to insert another row in that time window, would result in a duplicate key error, that you can catch and take appropriate action.
SQL Fiddle
Uncomment the last insert to see the error on build schema.
i want to minus purchase date with datenow. i have table named count_sec :
|user_id| purchasedate |second|
| 1 |2015-06-06 08:36:05| |
| 2 |2015-06-06 08:36:15| |
example time now is 2015-06-06 08:37:00
what is the code if i am want the code to update the second to:
|user_id| purchasedate |second|
| 1 |2015-06-06 08:36:05| 55 |
| 2 |2015-06-06 08:36:15| 45 |
thank you
EDIT
i have already create this php, but the code is not work, how to fix?
<?php
require 'database/db.php';
$selectprchsdate = $mysqli->query("SELECT purchasedate FROM count_sec");
$row = mysqli_fetch_assoc($selectprchsdate);
$date = date('Y-m-d H:i:s');
$result = $date - $row['purchasedate'];
$mysqli->query("UPDATE count_sec
SET second = '".$result."'");
?>
In PHP you can use
// get current date and time
$now = new DateTime();
// create DateTime object for purchase date
$purchaseDate = DateTime::createFromFormat('Y-m-d H:i:s', $row['purchasedate']);
// calculate seconds
$seconds = $now->getTimeStamp() - $purchaseDate->getTimeStamp();
But the SQL solution suits this question better.
Try with the SQL query:
SELECT UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(purchasedate) as second from countsec
or this:
SELECT TO_SECONDS(NOW()) - TO_SECONDS(purchasedate) as second from countsec;
From MySQL Date and Time Functions
I am not understanding why you need to store this in a column in the table. As soon as it's stored, the value is old, and it will need to be updated again. (Don't do this.) But setting that issue aside for a moment...
As to why your code isn't "working"... your UPDATE statement is updating every row in the table. You've previously fetched one row from the table, and then calculated one value, and then the UPDATE statement doesn't have a WHERE clause to identify which row(s) you want to update, so every row gets updated with the same value. That's a big part of why your code isn't working.
And, there's no need to run a SELECT statement before you run an UPDATE. If you want to update all rows in the table, you set the column to an expression that returns the number of seconds between the current date and time and the date and time stored in purchasedate column.
One convenient way to do that is to use the UNIX_TIMESTAMP function to convert each of the DATETIME values into an integer value (number of seconds), and subtract them. For example:
UPDATE count_sec
SET `second` = UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(purchasedate)
As an alternative, you could use the TIMESTAMPDIFF function for an equivalent result:
UPDATE count_sec
SET `second` = TIMESTAMPDIFF(SECOND,NOW(),purchasedate)
But back to the issue of why this is wrong. You do not want to store second column in the table.
When you run a SELECT statement to return a row from the table, the value in this column is going to old.
Instead, you could just return a calculated value, calculated as of the time the SELECT statement runs, by including one of those expressions in the SELECT list. For example:
SELECT user_id
, purchasedate
, UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(purchasedate) AS `calc_second`
, `second` AS `old_stored_value`
FROM count_sec
ORDER BY user_id
The point I'm trying to emphasize here... do not store the second value in the table. You'll be chasing it, and continuously updating every row in table, whether that's every five minutes or every five seconds. And the stored value is always going to be "old".
Why do you need that? If you want to find out which rows in the table have second between 60 and 120, for example, if you intend to run this query:
SELECT user_id
FROM count_sec
WHERE second > 120
AND second <= 60
You could just as easily rewrite that based on purchasedate
SELECT user_id
FROM count_sec
WHERE purchasedate > NOW() - INTERVAL 120 SECOND
AND purchasedate <= NOW() - INTERVAL 60 SECOND
And, you won't be "chasing" continuous updates of the rows in the table, generating rollbackup, recording changes in the InnoDB log, writing the UPDATE statements in the binary logs. If you are running replication slaves, those statements have to be read from the log and re-executed on the slaves. All in all, storing second is just a poor design choice.
You can use TIMESTAMPDIFF() function like below. See Documentation
SELECT TIMESTAMPDIFF(SECOND, NOW(), purchasedate)
from count_sec;
(OR) if you want to UPDATE
UPDATE count_sec SET `second` = TIMESTAMPDIFF(SECOND, NOW(), purchasedate);
Per your comment, if you want to delay for 5 minutes then either you can use
SLEEP(seconds) function
(OR)
Wrap your updation code in a stored procedure and run that in every 5 minutes (probably using some scheduler job)
I have a table where I have column name 'date' and another column with the name 'status' if I use a cron job to run everyday and check if the date is older than 30 day then to change the status to expired, what code do I need to run using mysqli and php.
MySQL event scheduler is more better.
Start MySQL event scheduler by executing following query in PhpMyAdmin or MySQL command prompt.
Enter this.
SET GLOBAL event_scheduler = 1;
This will update your table.
CREATE EVENT newEvent
ON SCHEDULE EVERY 1 DAY
DO
UPDATE table SET status="expired" WHERE datefield<=CURRENT_DATE - INTERVAL 30 DAY;
Try this:
UPDATE table SET status="expired" where YOURDATEFIELD < date_sub(now(), interval 1 month);
Use INTERVAL in your UPDATE query..
UPDATE table SET status="expired" WHERE datefield<=CURRENT_DATE - INTERVAL 30 DAY
I want to insert data into a table on 1st day of every month. And it has to be just for one time. I mean one row for each 1st day of month. I am doing all this in a PHP file and using mySql.
So far i got this much-
if(Date('j')==1)
{
$query = select 1 from table where extract (year from t1) = extract(year from now()) and extract(month from t1) = extract(month from now()) LIMIT 1
if (#mysql_num_rows(mysql_query($query)) == 0)
{
//perform insert operation
}
}
I haven't tried this query till yet.
Maybe this will do the trick
SELECT * FROM xxx WHERE (DATE_FORMAT(CURDATE() ,'%d')==1)
SELECT DATEADD(mm, DATEDIFF(mm,0,GETDATE())-1,0) as StartOfLastMonth
SELECT DATEADD(mm, DATEDIFF(mm,0,GETDATE()),0) as StartOfThisMonth
SELECT DATEADD(mm, DATEDIFF(mm,0,GETDATE()),0) as StartOfNextMonth
Try out below event scheduler
CREATE EVENT myevent
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 MONTH
DO
"YOUR QUERY"
Your have to run this on the date on which you want to run on 1 month interval.
You get more information on http://dev.mysql.com/doc/refman/5.1/ja/create-event.html
You have two solutions, depending on what you exactly want.
If your data must be inserted at the first day: the only way is to insert it using a cron job which run at the correct time. You can use the mysql scheduler to do the job if it's only mysql related.
If your data need to be in the table after the first day, but you don't care if it is added in realtime or only when you access that data then you don't need a cron job. You can check for that data when you access it, then insert it before reading if it's not already present.
you can achieve with mysql event scheduler--
http://dev.mysql.com/doc/refman/5.1/en/events.html
CREATE EVENT IF NOT EXISTS `my_old_data_cleaner_event`
ON SCHEDULE EVERY 23 DAY_HOUR
COMMENT 'Clean up Service Start at 11:00PM daily!'
DO DELETE FROM my_table WHERE created_date < (NOW() - INTERVAL 1 MONTH);
OR for Stored Procedure.
CREATE EVENT IF NOT EXISTS `my_old_data_cleaner_event`
ON SCHEDULE EVERY 23 DAY_HOUR
DO CALL my_sp_cleanup_old_data();