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

1
  • 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. Commented Apr 4, 2012 at 15:12

1 Answer 1

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

Did the trick! ))

Sign up to request clarification or add additional context in comments.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.