0

I am trying to store the date as NULL when user not entering any value from datepicker

DatePicker HTML

<div class="form-group">
    <label >Date of Birth</label>
    <!-- <input type="date" class="form-control" id="ac_date_of_birth" name="ac_date_of_birth" placeholder="Enter Date"> -->
    <input type="text" class="form-control " id="ac_date_of_birth" name="ac_date_of_birth" tabindex="2" placeholder="Enter Date">
</div> 

datepicker JS

$('#ac_date_of_birth').datepicker({
        uiLibrary: 'bootstrap4',
              format:'dd/mm/yyyy'
});

At Front end my date Format is dd/mm/yyyy like 25/04/2019 and I converted it to YY/mm/dd to store in Mysql Database

Here is my Codeigniter Code

$userInfo   =   $this->input->post();

$ac_date_of_birth = strtotime($userInfo['ac_date_of_birth']);
if (empty($userInfo['ac_date_of_birth'])) {      
  $ac_date_of_birth=NULL;

} else {
   $ac_date_of_birth = str_replace('/', '-', date('Y-m-d', strtotime($userInfo['ac_date_of_birth'])));

}

I want to store NULL in case user not select date or when the select selected date will be store currently, it stores 1970/01/01

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Shareque
  • 361
  • 4
  • 23
  • [Set html datepicker to null](https://stackoverflow.com/q/27831248/2943403) – mickmackusa Apr 29 '19 at 12:47
  • 2
    Why are you trying to save with `YY/mm/dd`? Your table column is a DATE type column right? Does the table / environment permit a null date value? A date should be stored as `Y-m-d`. Can you set a default value of `null` for that column and if the user doesn't provide a date, just omit that value/column from your query. – mickmackusa Apr 29 '19 at 12:53
  • 1
    Actually @mickmackusa I think OP is converting correctly to `date('Y-m-d'` but lord alone knows why that is dont as part of a str_replace to remove `/` that are not there :)# – RiggsFolly Apr 29 '19 at 12:56
  • 1
    What are you replacing with this: `str_replace('/', '-', date('Y-m-d', strtotime($userInfo['ac_date_of_birth'])))`? – mickmackusa Apr 29 '19 at 12:56
  • some date picker returns with / format and some with a - hyphen and MySQL required hyphen - format that's why I use this @mickmackusa – Shareque Apr 30 '19 at 03:32
  • But you are dictating `date('Y-m-d')`. Your str_replace() call can be safely omitted. If you need to replace, replace at `$userInfo['ac_date_of_birth']`. – mickmackusa Apr 30 '19 at 03:35
  • I found this solution if (!empty($userInfo['ac_date_of_birth'])) { $data['user_date_of_birth'] = implode('-', array_reverse(explode('-', $userInfo['ac_date_of_birth'] ))); } – Shareque Apr 30 '19 at 04:58

0 Answers0