简体   繁体   中英

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

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?

When possible, try to use CI's query builder to lower the chances of syntax errors. As per Codeigniter Documentation :

$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:

$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

The third paramater of false tells CI to not protect the query with backticks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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