using insert() method to insert DateTime value with PHP Doctrine\DBAL 2
Asked Answered
M

1

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()?

Masticatory answered 4/4, 2012 at 14:59 Comment(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.Masticatory
M
26
$DB->insert('table_name', [
    'foo'   => 'foo',
    'bar'   => 17,
    'field' => new \DateTime(),
], [
    PDO::PARAM_STR,
    PDO::PARAM_INT,
    'datetime',
]);

Did the trick! ))

Masticatory answered 5/4, 2012 at 9:21 Comment(1)
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?Baalbek

© 2022 - 2024 — McMap. All rights reserved.