HunderingThooves
HunderingThooves

Reputation: 992

Html form - php - mysql date field?

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!

Upvotes: 0

Views: 3989

Answers (1)

Jared Farrish
Jared Farrish

Reputation: 49208

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)

Upvotes: 1

Related Questions