![](/img/trans.png)
[英]insert null date / time into mysql with php causing 0000-00-00 / 00:00:00
[英]Date and time from PHP writes 0000-00-00 00:00:00 in MySQL
我有一个带有JS datepicker用于日期和时间的PHP,它将所有字符串以这种格式“ 19.08.2012 @ 20:18”保存在一个称为$ date的变量中。
如果我将此变量直接放在查询中,它将在数据库中写入“ 0000-00-00 00:00:00”。 目前,我的头部有一个大黑洞,因此需要帮助。
如何在数据库中写入正确的选定日期和时间?
抱歉,我认为不是那么重要,这是代码。
index.php
<script type="text/javascript">
$(function() {
$("#date").datetimepicker({
dateFormat:'dd.mm.yy',
separator: ' @ '
});
});
</script>
<form action="setting.php" method="post">
<table>
<tr>
<td><label for="date">Date:</label></td>
<td><input type="text" id="date" name="date"/></td>
</tr>
</table>
<input type="submit" name="submit" />
setting.php
if(isset($_POST['save_autoresp'])) {
create($_POST['date']);
header("Location: admin.php");
exit();
} else {
header("Location: index.php");
exit();
}
functions.php
.......
.......
// Write the fields to the table
$query_create = mysqli_query($link, "INSERT INTO table VALUES (null, '$id', '$date')") or die ('Could not connect: ' . mysqli_error($link));
.......
.......
MySQL数据库中的日期字段为“ datetime”。
您收到的日期格式是MySQL无法识别的。 您必须首先将其转换为可接受的日期和时间文字 ,然后才能将其传递给INSERT。
可以通过两种方式完成此转换:
无论您选择哪种方式,在保存到数据库时,都使用Year-Month-Day格式保存日期,这样您就不会发现为什么“ 08/02”被认为是8月2日而不是8月2日。 2月8日。
您将需要转换变量以为MySQL指定正确的格式,即YYYY-MM-DD HH:NN:SS。 就这样。 通过向其抛出子字符串函数来完成。
如果直接在查询中写入字符串“ 19.08.2012 @ 20:18”,MySQL根本无法解析它。 您必须首先将其转换,具体取决于字段(列)是INT,TIMESTAMP还是DATETIME。
MySQL附带了一些方便的日期计算功能 ,因此您应该坚持使用DATETIME。
在PHP中,您可以使用gmmktime()
和gmdate()
。 为了使您的生活更轻松,请确保MySQL服务器在UTC上运行,并且您的应用程序在将日期插入UTC之前将其转换为UTC。
在获取输出日期时,只需使用适当的date_default_timezone_set()
。
您需要将日期转换为mysql日期格式,可以使用explode()函数删除“。” 首先从您的日期签名,然后使用mktime()函数制作mysql日期格式
$date = exolode('.', $_POST['date']);
$unixtime= mktime(0, 0, 0, $date[1], $date[0], $date[2]);
$date1 = date("H-m-d H:i:s", $unixtime);
$final_Date = strtotime($date1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.