Shri Suresh
Shri Suresh

Reputation: 473

How to use MySQL functions in CakePHP save() function

I've MySQL Query like this

INSERT INTO users (firstname, amount) VALUES ('Suresh', ABS('-400'));

It inserts data like this

Suresh | 400

Same Query with CakePHP Model

$this->User->query("INSERT INTO users (firstname, amount) VALUES ('Suresh', ABS('-400'))");

It inserts data like this

Suresh | 400

Now My Question is How Can I use MySQL functions with CakePHP save() function

if ($this->request->is('post')) {
     $this->User->create();
     $this->request->data['User']['firstname'] = "Suresh";    //This is inserting in database
     $this->request->data['User']['amount'] = "ABS('-400')";  //This is not inserting in database
     $this->User->save($this->request->data);
}

Please let me know where I'm doing wrong?

Upvotes: 2

Views: 791

Answers (2)

Mr EdgarP
Mr EdgarP

Reputation: 161

You could try to use a DboSource expression, for example:

$this->request->data['User']['amount'] =
    $this->User->getDataSource()->expression('ABS(-400)');

Expression objects are not going to be sanitized or escaped, but inserted into the query as is.

A word of warning, be careful what you are passing, in case the -400 would actually be user input, you would need to make sure that it is being sanitized/casted/validated properly!

See also

Upvotes: 3

Alimon Karim
Alimon Karim

Reputation: 4469

Change your code

$this->request->data['User']['amount'] = "ABS('-400')";  // here you are sending string.

To

$this->request->data['Album']['amount'] = ABS('-400'); 

Upvotes: 0

Related Questions