0

Assume that I'm adding the date / time into a mysql database and have the following (small for once) chunk of code.

<input type="text" name="date">Leave time null for current<br />
<input type="Submit" name="submit" value="submit">

The Following is the form that catches that

$radate=$_POST['date'];
if ($radate=="")
$radate = date('Y-m-d H:i:s');
else {}

I've tried entering "2011-08-14 19:15:25" and it has returned all 0's, can someone help me out with this? Thanks a ton!

1 Answer 1

1

You would probably be better off using strtotime() to validate the date/time submitted, if it's a freeform date entry field especially. Otherwise, someone may miss-enter a date/time and unexpectedly have it use the current date/time instead.

$radate_valid = false;
$radate = $_POST['date'];
if (!$radate)
    $radate = date('Y-m-d H:i:s');
if (strtotime($radate) === false)
    $radate_valid = false;
else
    $radate_valid = true;

// Somewhere else
if ($radate_valid !== true) 
    /* Do something to warn the user. */

http://codepad.org/x2eZay0Q

If you used dropdowns, and the time was not a factor, you could also use checkdate(), although from your example it looks like you do need the time.

However, what you have posted should work. Here is an example using your date you provided:

http://codepad.org/BK1yqyMT

(And here without fixing the if block: http://codepad.org/p3CfmOJK)

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

3 Comments

Awesome, I didn't even know that this existed!
I've been doing PHP for seven years now, and I still come across functions/capabilities that I wasn't aware of that have existed for a long time.
Note, I just realized something... You need to test for validation in addition to the date check when it is provided. Sorry about that. See my last edit.

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.