I'm using db_insert() to insert a record into a table. That table as a "creationDatetime" field which should be set to now() on insert. I tried setting it to REQUEST_TIME, but that value is a unixtime value and not an sql datetime format so I get an error.

I suppose I could write a php function that will automatically format REQUEST_TIME as an sql datetime value and call that function every time I try to insert, but does anyone else have a better solution?

  • 1
    why don't you write now() itself in query ? – Ashu Jun 29 '12 at 4:53
  • 1
    Because you don't write a query when using db_insert(), the API constructs the query itself, and putting "now()" as the field value throws an error. – Kenny Wyland Jun 30 '12 at 0:08

I don't think you'll find a better solution to be honest. Classes like the SelectQuery provide an addExpression() function so that arbitrary expressions can be added (like NOW() etc), but unfortunately the InsertQuery class provides no such method.

Looks like you're stuck writing the helper function, or building up the SQL string yourself and running it through db_query() (I can't say I'd advise the second method though, and I'm sure I've seen it specifically recommended against in the docs somewhere).


Using a slightly different syntax (drupal_write_record):

$new_record = array(
    'field' => $form_state['values']['field'],
    'timestamp' => date("Y-m-d H:i:s", time()), //<- this
drupal_write_record('table_name', $new_record);
  • This ony saves the date not the time. hOW TO SAVE ALSO THE TIME? :) – alyssaeliyah Jul 15 '15 at 9:23
  • this not work time diff in both server – Saurabh Chandra Patel Feb 11 '17 at 14:17

db_insert() returns an InsertQuery object. It allows you to set any field value you want to set. Just use the php time() function to pass in the current unix time stamp.

  • As I explained in my post, I don't want the unix time, I want an sql date format. – Kenny Wyland Jun 30 '12 at 0:09

Let to chime in but here is a solution. Just use db_query. Here is my code I used that worked. And yes, this is a Drupal 7 solution. Thanks.

$query = "INSERT INTO {company_cmi_session_time} uid,scoid,gid,datetime,initialize,terminate) VALUES (:uid,:scoid,:gid,NOW(),1,1)";
$result = db_query($query, array(':uid' => $uid, ':scoid' => $nid, ':gid' => $groupid));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.