Php 如何在手动创建的查询中防止SQL注入?

Php 如何在手动创建的查询中防止SQL注入?,php,cakephp,cakephp-2.0,cakephp-2.3,Php,Cakephp,Cakephp 2.0,Cakephp 2.3,我使用的是cakephp,下面的查询包含我知道的sql注入。但问题是如何在同一个查询中解决这个问题。我不想用其他方法。请不要取消它 Search->query("select * from subcategories where subcat_name like '%".$_GET['searchkey']."%' and subcat_status='active' "); 您应该完全避免这种构造查询的方式。 由于您已经标记了cakephp 2.0,2.3 Sanitize::esca

我使用的是cakephp,下面的查询包含我知道的sql注入。但问题是如何在同一个查询中解决这个问题。我不想用其他方法。请不要取消它

Search->query("select * from subcategories where subcat_name like '%".$_GET['searchkey']."%' and subcat_status='active' ");

您应该完全避免这种构造查询的方式。 由于您已经标记了cakephp 2.0,2.3 Sanitize::escape(string,conn)可能适合您的需要

Search->query(Sanitize::escape("select * from subcategories where subcat_name like '%".$_GET['searchkey']."%' and subcat_status='active'"));
我不想用其他方法

您应该使用任何提供所需功能的方法,而不是您更喜欢的方法

另外,您不应该直接在CakePHP中访问超全局函数,这只会给您带来麻烦,尤其是在单元测试中。使用请求对象提供的正确抽象方法,即
CakeRequest::query()


使用事先准备好的陈述 也就是说,使用准备好的语句,或者通过传递值绑定到
Model::query()
的第二个参数:

或者使用
DboSource::fetchAll()
,它也接受参数作为第二个参数:

$db = $this->Search->getDataSource();
$result = $db->fetchAll(
    "select * from subcategories where subcat_name like ? and subcat_status='active'",
    array('%' . $this->request->query('searchkey') . '%')
);
手动逃生 为了完整性起见,也可以通过
DboSource::value()
手动转义该值,但是您应该避免以这种方式构造查询字符串,因为一个小错误可能导致插入未转义的值,从而创建一个可能的SQL注入漏洞:

$searchkey = $this->request->query('searchkey');

$db = $this->Search->getDataSource();
$value = $db->value('%' . $searchkey . '%', 'string');

$result = $this->Search->query(
    "select * from subcategories where subcat_name like $value and subcat_status='active'"
);

永远不要将不受信任的数据直接添加到查询字符串中。使用准备好的/参数化的查询。@JimL hi我需要示例,所以请避免建议您可以在cake文档中找到一个示例…cake 2.x似乎支持准备好的/参数化的查询,这是一个比试图逃避查询更好的解决方案。sir您能解决这个问题吗hi sir,但在这种情况下,ids=41589572将其转换为字符串
$searchkey = $this->request->query('searchkey');

$db = $this->Search->getDataSource();
$value = $db->value('%' . $searchkey . '%', 'string');

$result = $this->Search->query(
    "select * from subcategories where subcat_name like $value and subcat_status='active'"
);