【问题标题】:date and time is not inserted in my sql database日期和时间未插入 mysql 数据库
【发布时间】:2014-05-26 09:32:07
【问题描述】:

我在 mysql 数据库中插入 datetime 对象,查询不执行。即没有插入发生。其中 db 中 current_time 和 expiry_time 的数据类型是日期时间。这是我的代码。请说明我的错误。我将非常感谢。

if($timespan == '3 days') {$expiry_time = date('Y-m-d H:i:s', strtotime('+3 days'));}
if($timespan == '5 days') {$expiry_time = date('Y-m-d H:i:s', strtotime('+5 days'));}
if($timespan == '7 days') {$expiry_time = date('Y-m-d H:i:s', strtotime('+7 days'));}

$dt = new DateTime();
$dt->format('Y-m-d H:i:s');
$dt = serialize($dt);
$sql="INSERT INTO survey (user, title, description, opta, optb,optc,optd,uploaded,current_time,expiry_time) VALUES ('$user','$title', '$dis', '$a' , '$b', '$c', '$d','','$dt','$expiry_time')";
if (mysqli_query($con,$sql))
 {
  echo "Success";
 }
 else
  {
  echo "Error: " . mysql_error();
  }

【问题讨论】:

  • current_time 的数据类型是什么?
  • 你有异常吗?
  • 你序列化 $dt 有什么原因吗?
  • 为什么要序列化 ​​$dt?
  • 为什么不$expiry_time = date('Y-m-d H:i:s', strtotime('+' . $timespan));

标签: php mysql datetime phpmyadmin sql-insert


【解决方案1】:

因为$dt->format('Y-m-d H:i:s'); 返回一个字符串并且不会将$dt DateTime 对象转换为字符串。将$dt->format('Y-m-d H:i:s'); 的输出保存到变量中并插入。

【讨论】:

    【解决方案2】:

    你可以使用mysql NOW()

    $sql="INSERT INTO survey (user, title, description, opta, optb,optc,optd,uploaded,current_time,expiry_time) VALUES ('$user','$title', '$dis', '$a' , '$b', '$c', '$d','',NOW(),'$expiry_time')";
    

    【讨论】:

      猜你喜欢
      • 2013-04-27
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      • 1970-01-01
      • 2014-07-07
      • 2011-02-25
      相关资源
      最近更新 更多