在 MySQL/PHP 中存储用户生日的最佳方式是什么?
在 MySQL/PHP 中存储用户出生日期的最佳方法是什么?为什么?
我目前将其存储为以下格式的 VARCHAR(10)
:
MM-DD-YYYY
...但我感觉这不是最好的方法,特别是因为我有时会在该字段中看到无效的年份。
请不要只是说出最好的方法是什么,还要解释为什么它是最好的方法,以便我可以说服我改变网站上处理生日的整个方式,如果需要的话,这是一项艰巨的任务。
谢谢。
What is the best way to store user BIRTHDATES in MySQL/PHP and why?
I'm currently storing it as a VARCHAR(10)
in the following format:
MM-DD-YYYY
...but I have a feeling this isn't the best way, especially since I sometimes see invalid years in that field.
Please don't just say what the best method is, also explain why it's the best method so that I can be convinced to change the entire way birthdates are handled on my site, which is a huge undertaking should that be needed.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
mySQL 有一个原生的日期字段类型:
日期
。不知道要给出什么进一步的解释:)如果您想在 mySQL 表中存储日期,
DATE
就是一个正确的选择。它为>
、<
和BETWEEN
等查询提供了优化的索引,排序速度快,并且可以处理 1001 年以来的任何日期-9999,所以这确实是正确的选择。mySQL has a native field type for dates:
DATE
.Not sure what further explanation to give :) If you want to store dates in a mySQL table,
DATE
simply is the one correct choice. It comes with optimized indexing for queries like>
,<
andBETWEEN
, sorts fast, and can deal with any date from the years 1001-9999, so this really is the way to go.将其存储为 DATE 类型,因为它对于涉及字段的存储和操作(按日期过滤等)都非常有效。
Store it as a
DATE
type, since it's very efficient for both storage and operations involving the field (filtering by date, etc.).正如其他人已经回答的那样:MySQL 有一个仅用于日期的 DATE 格式,但如果您需要时间和日期,还有 DATETIME 和 TIMESTAMP。
DATE需要3个字节的存储空间,DATETIME需要8个字节,TIMESTAMP需要4个字节
。顺便说一句,INT也需要4个字节。如果您只是使用没有相应时间的 DATE(例如您的生日),那么这并不是真正的问题,但是有 一篇文章,其中提出了一些关于为什么您可能希望避免使用 DATETIME 的论点,我认为值得一读。评论也值得一读,因为有些人注意到文章中的建议并不总是实用:例如,查询优化器有时在日期函数方面遇到问题,并且难以将日期存储为 unix 时间戳。
As others have already answered: MySQL has a DATE format for just dates, but if you need a time and date there's also DATETIME and TIMESTAMP.
DATE requires 3 bytes of storage, DATETIME require 8 bytes, and TIMESTAMP requires 4.
Incidentally, INT also requires 4 bytes. If you're just using a DATE without a corresponding time - like for your birthdays - then it's not really an issue, however there is an article which presents some arguments as to why you might want to avoid using DATETIME, and I think it's worth a read. It's also worth reading over the comments as some people have noted that the suggestions in the article aren't always practical: e.g. query optimiser sometimes has trouble with date functions, and the difficulty storing dates as unix timestamps.
这是带有验证的 php 部分,之前将 Err 变量声明为 null。
希望这有帮助
This Is the php part with verification do declare the Err variable to null before.
Hope this helps