【问题标题】:Insert date into MySQL in PHP在 PHP 中将日期插入 MySQL
【发布时间】:2018-03-30 09:53:59
【问题描述】:

如下所示,我尝试在event 表中插入类似2018-03-31 的日期,但没有成功。输入类型 date 的日期结果。它是我数据库中的DateTime,但知道时间对我没有用。那么,为什么是DateTime?因为如果用户不提供日期,我想要当前日期,而 DATE 数据类型我不能。

您能帮我解决这个问题并了解如何正确地将日期插入 MySQL 表。

$sql = "INSERT INTO event (titre,content,image,date) VALUES (?,?,?,?)";
$connexion = Connect::getConnexion();

try{
  $query = $connexion->prepare($sql);

  $d = date('Y-m-d',strtotime($date));
  $query->bindParam(1,$titre,PDO::PARAM_STR,100);
  $query->bindParam(2,$content,PDO::PARAM_STR,8000);
  $query->bindParam(3,$d,PDO::PARAM_STR);
  $query->bindParam(4,$image,PDO::PARAM_STR,8000);

  $connexion->beginTransaction();
  $query->execute();
  $lastInsert = $connexion->lastInsertId();
  $connexion->commit();
}

【问题讨论】:

  • " 00:00:00" 附加到日期的格式部分。 date 将按原样解析它。
  • 我不明白为什么当用户不提供日期时你不能使用DATE 类型。无论哪种方式,您都应该输入该列所期望的内容,因此要么更改它,要么正确输入它。
  • $d = date('Y-m-d 00:00:00',strtotime($date));不工作。对于我的数据库中的 DATETIME 格式,当我在我的 sql 管理面板中声明 DATE 类型并且我在默认值中选择“CURRENT_TIMESTAMP”时出现错误“默认值无效”。
  • 当 $date 为 "2018-03-31" 时,$d 为 "1970-01-01 00:00:00" 且 $d = date('Y-m-d 00:00:00', strtotime($date));
  • 在mysql的表结构中只能选择DATE

标签: php mysql date


【解决方案1】:

您正在日期行上设置图像值,并在图像行上设置日期值。交换dateimage的位置。我认为这可能会解决您的问题。如果不让我知道。

    $sql = "INSERT INTO event (titre,content,date,image) VALUES (?,?,?,?)"; 
//switch date and image like so
        $connexion = Connect::getConnexion();

        try{
          $query = $connexion->prepare($sql);

          $d = date('Y-m-d',strtotime($date));
          $query->bindParam(1,$titre,PDO::PARAM_STR,100);
          $query->bindParam(2,$content,PDO::PARAM_STR,8000);
          $query->bindParam(3,$d,PDO::PARAM_STR);
          $query->bindParam(4,$image,PDO::PARAM_STR,8000);

【讨论】:

  • 谢谢它的工作,我不明白我在提问之前怎么没有看到这个。
  • 那么请将我的问题标记为已接受的答案。也帮助我!很高兴我能帮上忙! :)
【解决方案2】:
  $d = date('Y-m-d',strtotime($date));
  $query->bindParam(1,$titre,PDO::PARAM_STR,100);
  $query->bindParam(2,$content,PDO::PARAM_STR,8000);
  $query->bindParam(3,$image,PDO::PARAM_STR,8000);
  $query->bindParam(4,$d,PDO::PARAM_STR);

试试这个

【讨论】:

    【解决方案3】:

    您不能在查询中的字段名称中写入日期,日期应该在波浪号之间(反引号转义)。

    【讨论】:

    • like this $sql = "INSERT INTO event (titre,content,image,date) VALUES (?,?,?,TIMESTAMP(?))"; ?
    猜你喜欢
    • 2011-07-20
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 2012-08-20
    • 1970-01-01
    相关资源
    最近更新 更多