php 在 Codeigniter 中转义 SQL 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10968527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Escaping SQL queries in Codeigniter
提问by Nyxynyx
I am inserting some data into a MySQL table using CodeIgniter. Because I am using INSERT IGNORE INTOand do not want to edit the active records class to enable this feature, I am generating the SQL query manually.
我正在使用 CodeIgniter 将一些数据插入到 MySQL 表中。因为我正在使用INSERT IGNORE INTO并且不想编辑活动记录类来启用此功能,所以我正在手动生成 SQL 查询。
$this->db->query("INSERT IGNORE INTO my_table(lat, lng, date, type)
VALUES ('" . $data['lat'] . "', '" . $data['lng'] . "', '" . $data['date'] . "', '" . $data['type'] . "')");
Problem:The query failed when the string in $data['type']contained a single quote. How can I make it such that these characters that need to be escaped gets escaped automatically, like when using Active records?
问题:当字符串中$data['type']包含单引号时查询失败。我怎样才能让这些需要转义的字符自动转义,就像使用活动记录时一样?
回答by Yan Berk
Another way is to use Query Binding which automatically escapes all the values:
另一种方法是使用自动转义所有值的查询绑定:
$sql = "INSERT IGNORE INTO my_table(lat, lng, date, type) VALUES (?,?,?,?);";
$this->db->query($sql, array($data['lat'], $data['lng'], $data['date'], $data['type']));
回答by Moyed Ansari
use $this->db->escape();it will escape the string automatically
使用$this->db->escape(); 它会自动转义字符串
This function determines the data type so that it can escape only string data. It also automatically adds single quotes around the data so you don't have to:
此函数确定数据类型,以便它只能转义字符串数据。它还会自动在数据周围添加单引号,因此您不必:
$this->db->query("INSERT IGNORE INTO my_table(lat, lng, date, type)
VALUES ('" . $this->db->escape($data['lat']) . "', '" . $this->db->escape($data['lng']) . "', '" . $this->db->escape($data['date']$this->db->escape . "', '" . $this->db->escape($data['type']) . "')");
Here is the reference Click Here
这是参考点击这里

