0

I'm trying to add date and time to a datetime field in mysql database using PHP.

My datetime in mysql database is stored like this:

2015-01-20 05:10:17

I tried to add 5 days to that field like this:

$Date = date();
$end_date = date("Y, n, j, G, i, s", strtotime($Date. ' + 5 days'));

UPDATE myTable SET end_date='$end_date' WHERE randKey='$id'

but when I look at the database for updates I see the end_date field like this:

0000-00-00 00:00:00

which means it has been updated but everything has been set to 0 for some reason!

could someone please advise on this issue?

Thanks in advance.

3 Answers 3

2

Check this:

$end_date = date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s"). ' + 5 days'));

MySql store the datetime in YYYY-MM-DD HH:MM:SS format.

Sign up to request clarification or add additional context in comments.

1 Comment

As far as I am aware, the real runtime difference between your solution and mine is that your solution includes a single extra string concatenation, which for something that is probably not high-throughput production code, is of trivial concern. I'd say that either solution should work pretty much identically.
2

Instead of trying to add the five days to the current date in one string, using the two parameters to strtotime would be much easier, as so:

$Date = date();
$end_date = date("Y, n, j, G, i, s", strtotime('+5 days', $Date));

The second parameter specifies what the "current" time is; that is, where to base the +5 days off of (start position). When unspecified, it defaults to time().

Comments

1

First, the code you provided doesn't add 5 days to the value of the field, but five days to today's date. See, if your field contains 2015-01-01 and as you wrote, you would like to add 5 days to this field, you shouldn't add five days in PHP to date() because it will be 2015-01-25 instead of 2015-01-06. So if you want to add 5 days to the field value use this:

UPDATE myTable SET end_date=DATE_ADD(end_date, INTERVAL 5 DAY) WHERE randKey='$id';

But if you want to add five days after today, use this:

UPDATE myTable SET end_date=DATE_ADD(CURDATE(), INTERVAL 5 DAY) WHERE randKey='$id';

If you care for the time also, not just the date, use NOW() instead of CURDATE().

I hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.