14

How can i pass PHP's DateTime object as a value for database field using Doctrine\DBAL?

$DB is a Doctrine\DBAL\Connection instance.

$DB->insert('table_name', [
    'field' => new \DateTime(),
]);

// Catchable fatal error: Object of class DateTime could not be converted to string

The code above is not working and documentation is scarce.

I knew for sure that you can provide DateTime objects directly using another DBAL methods, is it possible to do this with insert()?

Slava Fomin II
  • 26,865
  • 29
  • 124
  • 202
  • 1
    Solution found. Just pass third argument array('datetime') to the insert() method. Use 'datetime' for DateTime, PDO::PARAM_STR for strings and PDO::PARAM_INT for integers. – Slava Fomin II Apr 04 '12 at 15:12

1 Answers1

26
$DB->insert('table_name', [
    'foo'   => 'foo',
    'bar'   => 17,
    'field' => new \DateTime(),
], [
    PDO::PARAM_STR,
    PDO::PARAM_INT,
    'datetime',
]);

Did the trick! ))

Slava Fomin II
  • 26,865
  • 29
  • 124
  • 202
  • What about the order of the elements in the first array? I presume when array of key-value pairs is declared right as function argument, the order of the keys will match the order of them being declared, however what if key-value pair array is created dynamically by some other function? – Dimitry K Apr 18 '16 at 18:59