开发者

dates when saving to mysql database

in my php code I was asking the user to choose day, month and year from some dropdown fields where values where 1, 2, 3 etc instead of 01, 02, 03.

these were then combined to form a string like "YYYY-MM-DD" for the insertion in a db开发者_开发百科 (in a date field).

Having missed the initial 0, I thought I was sending strings in the wrong format, eg "YYYY-M-D" or YYYY-MM-D", but then I've noticed they appear in the right format in the database anyway: even if I submitted YYYY-M-D, it appeared as YYYY-MM-DD.

is this the normal behaviour of mysql? if so, can i just avoid worrying about changing the code in my application?


Yes, this is normal behaviour. If your column has type DATE, MySQL will convert the string to an internal representation of a date when inserting it. MySQL is flexible when parsing dates as long as the order is correct (year, month, day). When displaying dates it will use 'YYYY-MM-DD' regardless of the format you used when storing the data.

Here are some quotes from the relevant page of the manual:

MySQL displays DATE values in 'YYYY-MM-DD' format

MySQL retrieves values for a given date or time type in a standard output format, but it attempts to interpret a variety of formats for input values that you supply (for example, when you specify a value to be assigned to or compared to a date or time type). Only the formats described in the following sections are supported. It is expected that you supply legal values. Unpredictable results may occur if you use values in other formats.

Although MySQL tries to interpret values in several formats, dates always must be given in year-month-day order (for example, '98-09-04'), rather than in the month-day-year or day-month-year orders commonly used elsewhere (for example, '09-04-98', '04-09-98').


i recommend passing the input to mktime() and then format it with date(), this way you can be sure to always get the format you wanted.

besides you are a little better protected against injection attacks

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜