【问题标题】:DBAL : save DateTime in DBDBAL:将日期时间保存在数据库中
【发布时间】:2016-08-17 02:43:54
【问题描述】:

我正在尝试将 DatTime 对象保存在 MySQL 数据库中。在插入时,我有这个错误:

“执行'INSERT INTO event (name_event, desc_event, minimumPrice_event, startDate_event, endDate_event, startHour_event, endHour_event, num_ET) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' 时发生异常参数 ["rfreger", "gregregerg", 44, {"date":"2011-01-01 00:00:00","timezone_type":3,"timezone":"Europe/Paris"}, false, false , false, 2]: 可捕获的致命错误:DateTime 类的对象无法转换为字符串"

我不明白为什么该方法尝试将 DateTime 对象转换为字符串

如何解决这个问题?

public function save(Event $event) {
    $eventData = array(
        'name_event' => $event->getName(),
        'desc_event' => $event->getDesc(),
        'minimalPrice_event' => $event->getMinimalPrice(),
        'startDate_event' => $event->getStartDate(),
        'endDate_event' => $event->getEndDate(),
        'startHour_event' => $event->getStartHour(),
        'endHour_event' => $event->getEndHour(),
        'num_ET' => $event->getType()
        );

    if ($event->getNum()) {
        // The event has already been saved : update it
        $this->getDb()->update('event', $eventData, array('num_event' => $event->getNum()));
    } else {
        // The event has never been saved : insert it
        $this->getDb()->insert('event', $eventData);
        // Get the id of the newly created event and set it on the entity.
        $id = $this->getDb()->lastInsertId();
        $event->setNum($id);
    }
}

【问题讨论】:

  • 请将执行查询的代码贴出来
  • 这是$this->getDb()->insert('event', $eventData);
  • 你的 $sql 语句是在哪里创建的?您在问题中发布的大错误包括您的 SQL 语句,我们必须查看您尝试绑定到该语句的值以推断错误。因此,如果您可以找到将参数绑定到 (?, ?, ?.....) 问号的函数,那么该代码将非常有用
  • 我正在使用 Symfony & DBAL,我没有写任何 SQL 语句。 $this->getDb()->insert('event', $eventData);替换语句
  • SQL中startDate_event和endDate_event的数据类型是什么?此外,您将 false 作为 endDate_event 传递。

标签: php symfony datetime dbal


【解决方案1】:

使用 MySQL,首先创建一个称为 SQL 语句的字符串,然后将其发送到数据库以执行。您的代码创建的 SQL 语句类似于:

INSERT INTO event (name_event, desc_event, minimalPrice_event, startDate_event, endDate_event, startHour_event, endHour_event, num_ET) VALUES (?, ?, ?, ?, ?, ?, ?, ?)

在 php 中,您可以将字符串连接在一起以创建更长的字符串,如下所示:

$stringFinal = $stringA."other string".$stringB.$number4;

您甚至可以在其中添加数字。但是,某些数据类型不会转换为字符串。数组就是一个很好的例子。如果你有以下数组:

$myArray = array (
  [0] => 4,
  [44] => 'hello'
)

如果您尝试使用以下代码创建字符串:

$myString = "hello".$myArray;

运行脚本的服务器会完全糊涂,因为它的设计初衷不是将数组转换为字符串。

所以回答你的疑问:

我不明白为什么该方法会尝试转换 DateTime 对象 到一个字符串

它必须是一个字符串,因为这是您第一次查询 SQL 命令时数据库读取的格式。

您遇到错误的原因是因为您在代码中传递了一个变量(或多个变量)以插入到您的数据库中,该变量无法转换为字符串。

希望对你有帮助!

【讨论】:

  • 感谢 Webeng。你的解释真的很完整。所以,我改变了存储 DateTime 对象的方式。现在可以了,谢谢;)
  • @KyleCoupart 没问题老兄,随时:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-02
  • 2012-01-27
  • 2019-02-26
  • 1970-01-01
  • 2017-07-03
  • 2018-05-25
  • 2011-04-17
相关资源
最近更新 更多