2012-08-14 84 views
1

我想在CakePHP中執行SQL更新。這裏是我的代碼:cakephp SQL幫助!哪裏?

$sql = " 
    UPDATE carts 
    SET 
    qty = ".$this->data['Cart']['qty'].", 
    process = 'UnPaid' 
    WHERE ct_session_id = '".$this->data['Cart']['ct_session_id']."' 
    AND product_id = '".$this->passedArgs['pd_id']."' 
    AND key = '".$this->Session->read('Cart.key', $newCartkey)."' 
";  
$this->Cart->query($sql); 

我得到這個錯誤:

SQL Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key = 'bwfgkxms'' at line 3 

我的代碼生成的查詢是:

UPDATE carts 
SET 
    qty = 111, 
    process = 'UnPaid' 
WHERE ct_session_id = '3254430f577669bb8ecdb8b8aadf1b96' 
    AND product_id = '51' 
    AND key = 'bwfgkxms' 
+1

使用CakePHP,但忽略所有約定=可能不是一個好主意。 (使用CakePHP的save()功能 - 它可以幫你避免像這樣的麻煩) – Dave 2012-08-14 14:45:50

回答

8

key是MySQL中的reserved word,你需要將其包圍在列名中帶有反引號。

$sql = " 
UPDATE carts 
SET qty = ".$this->data['Cart']['qty'].", process = 'UnPaid' 
WHERE ct_session_id = '".$this->data['Cart']['ct_session_id']."' 
    AND product_id = '".$this->passedArgs['pd_id']."' 
    AND `key` = '".$this->Session->read('Cart.key', $newCartkey)."' 
"; 
+1

@DaveRandom你擊敗了我! :P謝謝你。 – nickb 2012-08-14 13:15:11

+4

這是一個協作的努力: - D - 可能值得一提的是Bobby Tables,看起來很像可疑的用戶對我的輸入... – DaveRandom 2012-08-14 13:16:25

0

如果養成使用CakePHP約定的習慣會大大有利於您。這樣做有許多好處,當您執行諸如手寫輕鬆使用CakePHP完成的查詢之類的操作時,您可能會讓自己更加困難,併爲自己解決許多問題/安全問題未來。

CakePHP的方式(與所有的利益包含在以下約定):

$this->Cart->updateAll(
    array(
     'Cart.qty' => $this->data['Cart']['qty'], 
     'Cart.process' => 'UnPaid'), 
    array(
     'Cart.ct_session_id' => $this->data['Cart']['ct_session_id'], 
     'Cart.product_id' => $this->passedArgs['pd_id'], 
     'Cart.key' => $this->Session->read('Cart.key', $newCartkey) 
    ) 
); 

更多細節上的更新數據(和/或保存在通用數據): http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-array-conditions