0

I have a registration form for a website which uses bootstrap datepicker module to handle "birthday" date in a format dd.mm.yyyy.

Input:

<input type="text" id="birthday" name="birthday" data-provide="datepicker" class="form-control datepicker" required />

JS:

$('.datepicker').datepicker({    
   format: "dd.mm.yyyy",    
   weekStart: 1,    
   autoclose: true  
});

When a user submits the form, this is how I get the birthday

$user->birthday=$_POST['birthday'];

and in the user creation class, I will sanitize the input with:

$this->birthday=htmlspecialchars(strip_tags($this->birthday));

Now, I want to save this into a MySQL table, and "birthday" column is formatted as DATE, so it has to have the format of Y-m-d. To do this, I tried to convert the date like so:

//since I get a string, first convert it to time, create a date from it and format it to Y-m-d and then bind it to the birthday parameter.
$birthday_converted = date_format(date_create(strtotime($this->birthday)),"Y-m-d");
$stmt->bindParam(':birthday', $this->birthday_converted);

When I do this, I get an error saying this:

Warning: date_format() expects parameter 1 to be DateTimeInterface, integer given

even though, the date will be written into the database, but incorrectly. For example, if the date picked is 16.03.2020 (March 16th), in DB I will get 2016-03-20

4
  • How about using STR_TO_DATE ? Fiddle test here Commented Mar 23, 2020 at 8:10
  • but as I see, this is something to use when reading from a database, while I'm looking for something to write a date into a DB Commented Mar 23, 2020 at 9:01
  • It can use to write/insert/update .. refer this example Commented Mar 23, 2020 at 9:17
  • 1
    Thanks! However, I solved it like this: $this->birthday=date_format(date_create(htmlspecialchars(strip_tags($this->birthday))),"Y-m-d"); Commented Mar 23, 2020 at 9:49

1 Answer 1

1

I actually just added "the conversion" into the "sanitization" part:

$this->birthday=date_format(date_create(htmlspecialchars(strip_tags($this->birthday))),"Y-m-d");

And then I have a clean birthday ready for binding to a parameter.

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

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.