简体   繁体   English

如何使用PHP在MySQL数据库中存储日期?

[英]How can I store a date in a MySQL database using PHP?

I want to store a date value in a MySQL database. 我想在MySQL数据库中存储日期值。

I have one PHP page called A.php that has 3 inputs: d , m , y , where d = (1 ... 31) , m =(1 ... 12) and y = (1970 to 2009) . 我有一个名为A.php PHP页面,它有3个输入: dmy ,其中d = (1 ... 31)m =(1 ... 12)y = (1970 to 2009)

Now in b.php I collect this values and I need to store in my db. 现在在b.php我收集这些值,我需要存储在我的数据库中。

My DB has a field called dob which is of date type. 我的数据库有一个名为dob的字段,它是日期类型。

How can I construct a variable of type date from d , m , y and store it in the DB? 如何从dmy构造日期类型的变量并将其存储在DB中?

mysql日期字段采用'yyyy-mm-dd'格式,因此请将其存储,但将其作为字符串从PHP传递,包括破折号。

You can just pass it a string: 你可以传递一个字符串:

$sql = 'insert into tbl (dob) values 
        (\'' . $month . '/' . $day . '/' . $year . '\')';

MySQL will do the correct conversion for you, so you don't even have to worry about it. MySQL将为您进行正确的转换,因此您甚至不必担心它。

Make sure that you've done mysql_real_escape_string to prevent SQL injection on all of your variables. 确保您已完成mysql_real_escape_string以防止对所有变量进行SQL注入。

too long. 太长。 simply do: 简单地说:

$dt = sprintf("%'04s-%'02s-%'02s",$y,$m,$d);
mysql_query("insert into mytable (dob) values ('$dt')");

To construct a variable of type date, use the mktime() function: 要构造date类型的变量,请使用mktime()函数:

$date = mktime(0, 0, 0, $month, $day, $year);

To store your $date in your database, convert the date to a string: 要将$ date存储在数据库中,请将日期转换为字符串:

$sql = "INSERT INTO table (dob) VALUES ('" . date('Y-m-d', $date) . "')";

Alternatively, using mySQLi: 或者,使用mySQLi:

$query = $db->prepare('INSERT INTO table (dob) VALUES (FROM_UNIXTIME(?))');
$query->bind_param('i', $date);
$query->Execute();

It's best to just store it as a UNIX timestamp in the db since it's crossplatform using 最好只将它作为UNIX时间戳存储在数据库中,因为它是跨平台使用的

mktime()

Then, when you retrieve it from the db, use 然后,当您从数据库中检索它时,请使用

date()

to convert it to whatever format you want (eg October 31, 2009; 10/31/2009; etc) 将其转换为您想要的任何格式(例如2009年10月31日; 2009年10月31日;等)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM