简体   繁体   English

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

[英]Proper way to escape query in Codeigniter

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

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

The error: 错误:

You have an error in your SQL syntax; 您的SQL语法有误; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Upvotes' = 'Upvotes'+1 WHERE ID= 386464' at line 1 检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在第1行的“ Upvotes'='Upvotes'+ 1 WHERE ID = 386464'附近使用

Basically it's adding quotes around the Upvotes field causing it to be a malformed query what's the most practical way to remove the single quotes or rewrite the query entirely? 基本上,它在Upvotes字段周围添加引号,导致它成为格式错误的查询,什么是删除单引号或完全重写查询的最实用方法?

When possible, try to use CI's query builder to lower the chances of syntax errors. 如果可能,请尝试使用CI的查询生成器来降低语法错误的可能性。 As per Codeigniter Documentation : 根据Codeigniter文档

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

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

In your case, you are probably looking for something like this: 就您而言,您可能正在寻找这样的东西:

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

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

Now, if you want to run a custom code that you cant run using CI's query builder class, then do this: 现在,如果要运行无法使用CI的查询生成器类运行的自定义代码,请执行以下操作:

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

The answers here arn't quite right, as they are expecting you to already have the upvote count. 这里的答案并不完全正确,因为他们希望您已经有了支持人数。 I think this is what you're looking for: 我认为这是您要寻找的:

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

Use the line below to confirm the output it should give you something like: 使用下面的行来确认输出,它应该为您提供:

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

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

The third paramater of false tells CI to not protect the query with backticks. false的第三个参数告诉CI不要用反引号保护查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM