1

我正在尝试在 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'
4

2 回答 2

8

key是 MySQL 中的保留字,需要在列名中用反引号括起来。

$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)."'
";
于 2012-08-14T13:13:27.593 回答
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 -条件

于 2012-08-14T17:42:25.467 回答