Sabyasachi Gupta Sabyasachi Gupta - 1 year ago 66
PHP Question

How to convert a string value to date

I am currently working on a form where an admin selects a date from 3 drop downs
and marks an employee as present or absent.

My attendance table has the following columns:

  • emp_id : int

  • date : date

  • status : varchar

I have 3 drop downs in an html form, one each for YYYY, MM and DD selection. I would like to capture these values as date and insert it into a date column in a table. How can I do that? I have tried searching for functions on the internet
but I haven't able to effectively use any one of them.

Any help will be appreciated.

Answer Source

Since the date will be inserted into MySQL, all these formatting with sprintf() or strtotime() is totally unnecessary.

MySQL expects date and time literals in the following formats for the date data type:

• As a string in either 'YYYY-MM-DD' or 'YY-MM-DD' format. A “relaxed” syntax is permitted: Any punctuation character may be used as the delimiter between date parts. For example, '2012-12-31', '2012/12/31', '2012^12^31', and '2012@12@31' are equivalent.

• As a string with no delimiters in either 'YYYYMMDD' or 'YYMMDD' format, provided that the string makes sense as a date. For example, '20070523' and '070523' are interpreted as '2007-05-23', but '071332' is illegal (it has nonsensical month and day parts) and becomes '0000-00-00'.

• As a number in either YYYYMMDD or YYMMDD format, provided that the number makes sense as a date. For example, 19830905 and 830905 are interpreted as '1983-09-05'.

Just produce one of the formats accepted by MySQL using simple string concatenation from the form input in php and then use this data as parameter in the insert sql statement.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download