php - 插入 DATE 意外行为。为什么?

标签 php mysql

我写了一个函数来重新排列数据库中存储的日期格式,从 d-m-yy-d-m。带有原始日期的原始字符串与插入查询一起正确存储,但格式化的字符串不是。

表结构:

+-------+------+
| Field | Type |
+-------+------+
| id    | INT()|
+-------+------+
| date1 | DATE |
+-------+------+
| date2 | DATE |
+-------+------+

PHP:

<?php
$db = new mysqli("localhost","root","","test");
function date2Store($date) {
    $dateFormat = DateTime::createFromFormat('d-m-y',$date);
    return $dateFormat->format('y-d-m');
}
$dateRaw = "22-01-17";
$dateFormatted = date2Store($dateRaw);
echo $dateFormatted; // Checking how the string looks
$query = "INSERT INTO dateTest(date1,date2) VALUES ('$dateFormatted','$dateRaw')";
echo $query; // Checking how the query looks
$db->query($query);
?>

结果是:

+----+------------+------------+
| id |  date1     |   date2    |
+----+------------+------------+
| 1  | 0000-00-00 | 2022-01-17 |
+----+------------+------------+

$query 输出:

INSERT INTO dateTest(date1,date2) VALUES ('17-22-01','22-01-17')

我检查过两者都是字符串,查询看起来是正确的。为什么他们存储不同?

最佳答案

17-22-01 不是有效日期,因此 - 根据您的 MySQL 服务器的配置 - 它不会存储在带有 DATE 的字段中类型。

如果你想存储你的源格式,它不是有效的 mysql 日期格式,可以使用另一种字段类型,p.e. varchar .

看看here into the MySQL manual发现 MySql 允许的日期格式 - 因此可以在您的 INSERT-statement 中使用:

MySQL recognizes DATE values in these formats:

  • 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'.

关于php - 插入 DATE 意外行为。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41791310/

相关文章:

php - Mysql 更新最大值(value)

php - 在 OS X : getting the timezone in PHP or from a command prompt in Terminal

php - 应使用哪种 PDO 绑定(bind)方法来提高安全性?

php - 三元 foreach 嵌套在 if/else 中

php - PHP 和 MySQL 中的 unicode 字符问题

PHP 无法从 mysql 查询获取列名

php - mysql_real_escape_string 和邮政地址数据

php - 如何在 PHP 中构建键组合数组

mysql - 加入不同的表并用mysql在一行上显示匹配记录

c# - 如何使用返回多个值的存储过程在 C# 中编写小巧玲珑?我想为下面提到的 SP 编写 dapper