在Codeigniter中转义查询的正确方法

时间:2015-03-16 18:28:14

标签: php mysql codeigniter

$sql = ("update Inventory SET  ? = ?+1 WHERE ID= ?");

$query = $this->db->query($sql, array($field,$field,$id))->affected_rows();

错误:

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   ''Upvotes'='Upvotes'+ 1 WHERE ID = 386464'在第1行

基本上它是在 Upvotes 字段周围添加引号,导致它成为格式错误的查询,删除单引号或完全重写查询的最实用方法是什么?

2 个答案:

答案 0 :(得分:2)

如果可能,请尝试使用CI的查询构建器来降低语法错误的可能性。根据 Codeigniter Documentation

$data = array(
    'title' => $title,
    'name' => $name,
    'date' => $date
);

$this->db->where('id', $id);
$this->db->update('Inventory', $data);

在你的情况下,你可能正在寻找这样的东西:

$data = array(
    'Upvotes' => $upvotes + 1
);

$this->db->where('CARD_ID', '386464');
$this->db->update('Inventory', $data);

现在,如果要运行使用CI的查询构建器类无法运行的自定义代码,请执行以下操作:

$custom_sql = "update Inventory SET Upvotes = Upvotes + 1 WHERE CARD_ID = 86464";
$query = $this->db->query($custom_sql);

答案 1 :(得分:2)

这里的答案并不完全正确,因为他们期待你已经有了upvote计数。我想这就是你要找的东西:

$this->db->where('ID', $ID);
$this->db->set('Upvotes', 'Upvotes+1', FALSE);
$this->db->update('Inventory');

使用下面的行确认它应该给你的输出:

echo $this->db->last_query();

UPDATE Inventory SET Upvotes = Upvotes + 1 WHERE ID = 386464

false的第三个参数表示CI不使用反引号来保护查询。

相关问题