pMan
pMan

Reputation: 9158

how to use mysql now() function in cakephp for date fields?

I have this code in my cakephp project:

$this->data['MyObject']['expire_date'] = 'NOW()';

and...

$this->MyObject->save($this->data);

But this won't save data in database. After googling I found I can use now() like this. But it seems wrong, what is the correct way to use it?

PS: My MySQL field is of type 'DATE'. It works if I use like this:

$this->data['MyObject']['expire_date'] = date( 'Y-m-d', mktime(0, 0, 0, date("m"), date("d")+30,   date("Y")));

Upvotes: 3

Views: 18144

Answers (5)

ᴍᴇʜᴏᴠ
ᴍᴇʜᴏᴠ

Reputation: 5256

For CakePHP 3 (in case someone's searching), you'd need to use the SQL functions:

$query = $this->Example->query();
$query
    ->insert(['created','id'])
    ->values(array(
        'created' => $query->func()->now(),
        'id' => $id,
    ));
$result = $query->execute();

Sources:

Upvotes: 0

Sabeeh Chaudhry
Sabeeh Chaudhry

Reputation: 6374

For cakephp 2.x users:

$db = $this->MyObject->getDataSource(); 


$this->data['MyObject']['expire_date'] = $db->expression('NOW()');

Upvotes: 9

JohnP
JohnP

Reputation: 50009

You can shorten that to

$this->data['MyObject']['expire_date'] = date('Y-m-d H:i:s'); 

By default, date() will take the present time, if you do not pass it a second 'timestamp' argument.

This method is preferable to calling DboSource::expression() especially when you want to set it in the controller for various reasons, instead of in the model.

Upvotes: 8

Guid
Guid

Reputation: 179

$this->data['MyObject']['expire_date'] = DboSource::expression('NOW()');

Upvotes: 17

Palani
Palani

Reputation: 7

$this->data['MyObject']['expire_date'] = strtotime('now');

Upvotes: -3

Related Questions