Reputation: 67
I have a text box where date is entered in php. Since I want the date to be in particular format I am using.
date("d.m.Y", strtotime())
to conver the date. When no date is give or if I leave the textbox blank it will enter 1970-01-01 to database. How can I solve this?
Here is my code
$d_date= clean($_POST['datum']);
$newdate = date("Y-m-d", strtotime( $d_date));
If $d_date
value is null the it will enter 1970-01-01 to database.
Upvotes: 3
Views: 9205
Reputation: 1150
you can use this to check strtotime return false or true
$from_date=strtotime($_POST["from"]);
$from_date=($from_date ? date("Y-m-d", $from_date) : '');
$to_date=strtotime($_POST["to"]);
$to_date=($to_date ? date("Y-m-d", $to_date) : '');
Upvotes: 1
Reputation: 53870
PHP strtotime()
returns false
on failure. This includes if the parameter is null, blank. or any other invalidly formatted string.
So, strtotime(null)
returns bool(false)
.
The second parameter for the date()
function is an integer, so when you call date("Y-m-d", false)
, false
gets converted to 0
, and date("Y-m-d", 0)
, returns the epoch date.
Here's an easy way to handle this, prior to inserting the value into the database:
// Default to null
$newdate=null;
// Only proceed if strtotime() succeeds
if($d_date=strtotime($_POST['datum'])) {
// Since we have a valid time, turn to date string
$newdate=date("Y-m-d", $d_date);
}
Then, simply allow NULL on your date column so that null can be inserted.
Upvotes: 1
Reputation: 1262
Make field in the database nullable, and when date is not submitted in the form set it to NULL. Default behaviour of mysql is to set date to default value, which is 1970-01-01(unix epoch)
Upvotes: 9