Yii – Updating a MySQL datetime column with now()

  • Yii Articles

  • Blog Subjects

  • Just a quick tip which took me a little while to figure out.

    If you have a “last_updated” column on your table and you want to update this manually in your code ten the easiest way would be use the MySQL NOW() function

     SQL |  copy code |? 
    1
    2
    UPDATE some_table SET last_updated_date=now();
    3

    However, and there is always a catch, if you try and use the now() function in a Yii prepared statement, it will try and update the column with the string “now()” and fail.

    What you need to do is to use a CDBExpression object as follows:-

     PHP |  copy code |? 
    1
    2
    $command->insert('some_table', 
    3
                       array(
    4
                                'id'=>$id,
    5
                                /.. other columns
    6
                                'last_updated_dt'=>new CDbExpression('NOW()')
    7
                            ));