【问题标题】:Best Way to Insert a unix timestamp using PHP into a mySQL integer field (INT)?使用 PHP 将 unix 时间戳插入 mySQL 整数字段 (INT) 的最佳方法?
【发布时间】:2016-09-29 14:19:00
【问题描述】:

我有一张表,并且 theDate 字段的结构为 INT (32) 。

编写 PHP 脚本 我想使用 mySQL PDO 将 unix 时间戳作为整数插入到 Date INT 表字段中。做这个的最好方式是什么?我的 theDate 字段最有效的大小是多少? 8、16、32?

代码:

$theDate = now();  // this returns a 0 in theDate mySQL field
    $stmt = $db->prepare("INSERT INTO countries(name, capital, language, theDate) VALUES (:country, :capital, :language, :theDate)");

$stmt->bindParam(':country', $country, PDO::PARAM_STR, 100);
$stmt->bindParam(':capital', $capital, PDO::PARAM_STR, 100);
$stmt->bindParam(':language', $language, PDO::PARAM_STR, 100);
$stmt->bindParam(':theDate', $theDate );
if($stmt->execute()) {
  echo '1 row has been inserted';  
}

我已经用谷歌搜索了这个并搜索了这个网站..找不到一个好的答案

谢谢

【问题讨论】:

  • 不要 - 改用正确的 datetime 字段;当您想按日期检索任何内容时,它会让生活变得更加轻松......不过,在这种情况下,您可能需要一个 timestamp 字段......我看不出有任何逻辑理由将日期存储在country 表,但要记录上次更新记录的时间。
  • 我和@CD001 在一起。最有效的大小是 DATETIME 字段,使用本机格式可以访问大量 additional functions 并使其易于阅读。请务必将这些时间插入为 UTC 以避免时区问题。如果相关,您可以在显示这些值时在 PHP 中进行任何时区转换。

标签: php mysql pdo unix-timestamp


【解决方案1】:

在 mysql 中存储日期时间信息的最佳方法是使用datetime 字段。你可以使用你正在尝试的very now() 函数。但当然你必须用 SQL 来调用它,而不是 PHP:

$sql = "INSERT INTO countries(name, capital, language, theDate) VALUES (?, ?, ?, now())";
$stmt = $db->prepare($sql);
$stmt->execute([$country,$capital,$language]);

如果你坚持使用不可靠和过时的 unix_timestamp,你必须使用unix_timestamp() SQL 函数而不是 now()。代码与上面相同,只是函数名不同。

如果您想通过 PDO 将 int 值发送到数据库 - 只需发送它:

$theDate = time();
$sql = "INSERT INTO countries(name, capital, language, theDate) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($sql);
$stmt->execute([$country,$capital,$language,$theDate]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 2013-07-20
    • 2019-08-21
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多