如何在CakePHP save()函数中使用MySQL函数

时间:2016-03-30 07:05:15

标签: php mysql cakephp cakephp-2.0

我这样的MySQL查询

Suresh | 400

它会插入这样的数据

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

CakePHP模型的相同查询

Suresh | 400

它会插入这样的数据

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);
}

现在我的问题是如何在CakePHP save()函数中使用MySQL函数

    #include <stdio.h>
    #include <time.h>

    int main(int argc, char **argv)
    {
            time_t timeNow;
            time_t timeAct;
            struct tm* time_info;
            time(&timeNow);
            time(&timeAct);
            time_info = localtime(&timeNow);
            char timeStr[sizeof"HH:MM:SS"];
            char timeN[sizeof"HH:MM:SS"];

            strftime(timeStr, sizeof(timeStr), "%H:%M:%S", time_info);
            printf("Time now: %s\n", timeStr);


            timeNow += 10;
            time_info = localtime(&timeNow);
            strftime(timeStr, sizeof(timeStr), "%H:%M:%S", time_info);
            printf("New time: %s\n", timeStr);

            time_info=localtime(&timeAct);
            strftime(timeN, sizeof(timeN), "%H:%M:%S", time_info);
            printf("time Actual: %s\n",timeN);


            while(1)
            {
                    if(strcmp(timeStr,timeN) == 0)
                    {
                            printf("hi");
                    }
            }
}

请告诉我我在哪里做错了?

2 个答案:

答案 0 :(得分:3)

您可以尝试使用DboSource表达式,例如:

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

表达式对象不会被清理或转义,而是按原样插入到查询中。

警告,请小心你传递的内容,如果-400实际上是用户输入,你需要确保它正在被正确消毒/铸造/验证!

另见

答案 1 :(得分:0)

更改您的代码

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

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