I was wondering if the following is possible to do through MySQL or will it have to be done using PHP.
Task - "Expiry Date"
User enters product name
User clicks submit form button
Data is POST'ed and then sent to MySQL
Expiry date = date now + 14 days
What I am trying to achieve is a way for mysql to insert an "expiry_date" in a table column that will equal 14 days after the date the row was created in that table.
e.g.
product_name - foo
entry_date - 2012-02-01
expiry_date - 2012-02-15
I have a feeling it may not be possible to do in mysql unless using a stored procedure.
I am happy to do it in PHP however I was hoping if I could do it with mysql it would leave less scope for error in my system.
Thanks
Create a table and set up a trigger for that table.
CREATE TABLE product(
product_id INT PRIMARY KEY,
product VARCHAR(40),
entryDate DATETIME,
expDate DATETIME
);
CREATE TRIGGER test_trigger BEFORE INSERT ON `product`
FOR EACH ROW SET
NEW.entryDate = IFNULL(NEW.entryDate, NOW()),
NEW.expDate = TIMESTAMPADD(DAY, 14, NEW.entryDate);
On each insert into the table, the trigger sets the entryDate to the current time and expDate to 14 days time.
You can use this by using DateTime methods in MySQL:
DATE_ADD(date_starts,INTERVAL 14 DAY)
for example:
UPDATE events SET date_starts = DATE_ADD(date_starts,INTERVAL 14 DAY) WHERE event_id = 3;
For more details go here.
you can try this this function
DATE_ADD(now(), INTERVAL 14 DAY);
date = DATE_ADD(NOW(), INTERVAL 14 DAY)
or as said, alter your table structure for that field (attribute for that field=) to "on Update CURRENT_TIMESTAMP"
According to this source you can't use expressions as a default specifier.
So not sure if it has changed since the bug was posted.
I'm not sure however why I assumed that the OP wants to define it as a default value.
I believe MySQL won't allow you to use expressions in the default value. You might want to write a trigger.
MySQL does provide a TIMESTAMP datatype which can be set to CURRENT_TIMESTAMP when a row is created or updated. You might find this feature somewhat useful:
CREATE TABLE table1 (
`Column1` VARCHAR(50) NULL,
`Created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
Once you're sure that MySQL is filling that column as expected, you can write queries like this:
SELECT `Created`, `Created` + INTERVAL 14 DAY AS `expiry_date`
FROM table1
The easiest way to solve that is just insert the value you want - without trigger or later update, eg.
INSERT INTO <your_table> (name, expiry_date) VALUES ('foo', DATE_ADD(CURRENT_TIMESTAMP,INTERVAL 7 DAY))
I like this format better:
SELECT NOW()+INTERVAL 14 DAY
Related
What would I enter into the "as defined" in phpMyAdmin for a default value of a timestamp field, to get +1 month from today?
Using MySQL 5.6.17, php 5.5.12, Apache 2.4.9, wampserver 2.5
I've tried
1 month
strtotime('+1 month')
From what I've read, the phpmyadmin "as defined" value is basically what the DEFAULT value will be in the CREATE TABLE query. If this is true, you can't actually provide a PHP function as your default value. You then have (at least) two options.
One, you can just set the value when you INSERT into your database:
$myDate = date('Y-m-d H:i:s', strtotime('+1 month'));
And run your query:
INSERT INTO myTable (myDate) VALUES ('{$myDate}');
(Though, you should use mysqli or PDO and data binding to set the value in your query. C.f. http://us1.php.net/pdo and http://us2.php.net/mysqli).
Two, or you could create a trigger:
CREATE TRIGGER myTiggerName
BEFORE INSERT ON myTable
FOR EACH ROW
SET NEW.myDate = DATE_ADD(NOW(), INTERVAL 1 MONTH);
This is probably the closest to what you're trying to do. It will set the myDate column to be NOW() + 1 MONTH whenever you insert a row into your myTable table.
In the above example, the trigger will always set myDate. If you just want to set it if the column is null, you could try:
CREATE TRIGGER myTiggerName
BEFORE INSERT ON myTable
FOR EACH ROW
IF NEW.myDate IS NULL THEN
SET NEW.myDate = DATE_ADD(NOW(), INTERVAL 1 MONTH);
END IF;
I would recommend handling this by your model, and not by SQL.
Try getting the date somewhat like this:
select timestamp + interval '2' day from xyz
In my table mytable. I have a column named session_time (float) where I store the time in microseconds when the row was added (I use the PHP function microtime(true) to get a float). How can I delete all rows from my table mytable which are older than 20 minutes?
I already tried something like this:
DELETE FROM mytable WHERE session_time < DATE_SUB(NOW(), INTERVAL 1800 SECOND)
But this deletes all rows!
UPDATED...
Instead of using php microtime(true) , you should use MySQL function NOW(). Delete the old column, and make a new one :
ALTER TABLE your_table ADD session_time DATETIME NOT NULL DEFAULT NOW();
Now when you add a row, it's session_time will be set to the current time automatically, and you do not need to insert any value for session_time.
Now for deleting all rows older than 30 minutes, use :
DELETE FROM your_table WHERE TIMESTAMPDIFF(MINUTE,session_time,NOW()) > 30;
Try
DELETE FROM myTABLE WHERE session_time < (now() - interval 30 minute)
I didn't test it. I think it shoud work as well.
It sounds like you're comparing a microsecond value generated in PHP, to a timestamp value generated in mysql. There's a few things that could go wrong here, since you may not actually be comparing time to time but time to float, or your PHP app is using a different clock than your mysql.
Since you're doing the comparison in SQL, you should save the session_time value based on SQL too. This is a good place for a default value, e.g.:
mysql> create table mytable ( id int not null, session_time timestamp default now() );
PHP microtime() uses unix timestamp format, not the DATETIME format. If you are storing things like that, you could use PHP to fill the query or use MySQL's unix_timestamp() function.
For PHP, it would be as simple as:
$query = 'DELETE FROM mytable WHERE session_time < '.time() - 1800;
I would recommend just using the DATETIME format on session_time though, you should take advantage of MySQL’s storage types.
I want to store current time (for example 00:30) in one of my column , the default CURRENT_TIMESTAMP gives both date and time which i dont want.
or is there any way of retrieving only time from CURRENT_TIMESTAMP ??
You can use MySQL's built-in TIME() function to extract the time part of a datetime expression. For example:
mysql> select time(now());
+-------------+
| time(now()) |
+-------------+
| 18:21:38 |
+-------------+
1 row in set (0.03 sec)
Since CURRENT_TIMESTAMP is a synonym for NOW(), you can just use TIME(CURRENT_TIMESTAMP).
Try combining TIME() and NOW():
SELECT TIME(NOW());
Output: 15:20:31
Of course, your column will need to be of type "TIME".
When you create the table set the column type to TIME
If I understand your question correctly, I think you have a timestamp column that has a default value of CURRENT_TIMESTAMP:
CREATE TABLE yourTable (
...,
...,
currentTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
If you just want to store the current time, and not the date part, you could use a TIME column and trigger, that will insert the time part automatically:
CREATE TABLE tableName (
...,
...,
currentTime TIME
);
CREATE TRIGGER currentTime BEFORE INSERT ON tableName
FOR EACH ROW
SET new.currentTime = TIME(NOW());
(an example is here) and you might also want to use an UPDATE trigger. Or you can just use CURRENT_TIMESTAMP, and get only the time part with TIME function:
SELECT TIME(yourTimestampColumn)
FROM yourTable
I'm working in PHP with a MySQL db and I have a current timestamp field which is created when the field is made, I then have another field which (when a page is hit) I would like a SQL statement to insert a replica of the timestamp - only 2 days ahead. Any ideas on how I would go about doing this?
So you have a table like:
id
current TIMESTAMP DEFAULT CURRENT..
another TIMESTAMP
?
You can do something like
UPDATE MyTable SET another = ADDDATE(current, INTERVAL 2 DAY) WHERE id = :myId
MySQL Date and Time functions
How about INSERT [...] (... , ADDTIME(NOW(),'2 00:00:00' , ...)
How do you add time or days to a current utc_timestamp?
I am using;
new CDbExpression('UTC_TIMESTAMP()')
for both 'created' and 'updated' fields in my mysql table but would like to add an 'expiry' field which would allow 4 days from creation date. I presume this is possible but am unsure how.
for insert/update current time
UPDATE table
SET created = NOW()
for 4 days from creation date
SELECT * FROM table WHERE created > DATE_SUB( NOW( ), INTERVAL 4 DAY )
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
In MySQL :
ALTER TABLE `table`
ADD expiry datetime DEFAULT DATE_ADD( utc_timestamp( ) , INTERVAL 4 DAY);
"The DEFAULT value clause in a data type specification indicates a
default value for a column. With one exception, the default value must
be a constant; it cannot be a function or an expression. This means,
for example, that you cannot set the default for a date column to be
the value of a function such as NOW() or CURRENT_DATE."
So, this is explicitely documented limitation
you have to create TRIGGER if your MySQL Version < 5.6.5
BUT
MySQL 5.6.5 changelog stats
As of MySQL 5.6.5, TIMESTAMP and DATETIME columns can be automatically
initializated and updated to the current date and time (that is, the
current timestamp). Before 5.6.5, this is true only for TIMESTAMP, and
for at most one TIMESTAMP column per table.
Reference :
http://bugs.mysql.com/bug.php?id=27645
http://optimize-this.blogspot.in/