我想将排序类型作为参数。所以我写了函数
public function findInterval($pageNumber, $limit, $sortType) {
$query = $this->_em->createQuery('Select c from Entities\Comment c where c.isremoved=0 ORDER BY c.creationdate ?1');
$query->setParameter(1, $sortType); //sortType is either ASC or DESC
return $users = $query->getResult();
}
但它不适用于致命错误 未捕获的异常'Doctrine \ ORM \ Query \ QueryException',消息'[语法错误]第0行,第77栏:错误:字符串的预期结束,在C:\ Users \ user \ Desktop \ projects \ interview \中得到'?'' application \ libraries \ Doctrine \ ORM \ Query \ QueryException.php:42堆栈跟踪:#0 C:\ Users \ user \ Desktop \ projects \ interview \ application \ libraries \ Doctrine \ ORM \ Query \ Parser.php(380): Doctrine \ ORM \ Query \ QueryException :: syntaxError('line 0,col 77:...')#1 C:\ Users \ user \ Desktop \ projects \ interview \ application \ libraries \ Doctrine \ ORM \ Query \ Parser。 php(745):Doctrine \ ORM \ Query \ Parser-> syntaxError('end of string')#2 C:\ Users \ user \ Desktop \ projects \ interview \ application \ libraries \ Doctrine \ ORM \ Query \ Parser。 php(213):Doctrine \ ORM \ Query \ Parser-> QueryLanguage()#3 C:\ Users \ user \ Desktop \ projects \ interview \ application \ libraries \ Doctrine \ ORM \ Query \ Parser.php(288): Doctrine \ ORM \ Query \ Parser-> getAST()#4 C:\ Users \ user \ Desktop \ projects \ interview \ application \ libraries \ Doctrine \ ORM \ Query.php(230):Doctrine \ ORM \ Query \ Parse r->解析()#5 C:\ Users \ user \ Deskt位于第42行的C:\ Users \ user \ Desktop \ projects \ interview \ application \ libraries \ Doctrine \ ORM \ Query \ QueryException.php
有没有其他方法如何按参数设置排序类型?
答案 0 :(得分:1)
首先,你将一个值直接放入你的DQL(c.isremoved = 0),正如Bram正确指出的那样,不应该出现。您应该只将参数“绑定”到查询中,这些参数将被正确转义并减轻任何潜在的SQL注入攻击。
其次,您使用的$ sortType参数应包含ASC或DESC。不确定您期望传递给此函数的值。但是,正如Bram所说,应对此进行测试,以确保您只使用这两个值中的一个。
public function findInterval($pageNumber, $limit, $sortType)
{
$sortType = ($sortType == 'ASC') ? $sortType : 'DESC'; // <-- this example defaults to descending
$query = $this->_em->createQuery('SELECT c FROM Entities\Comment c WHERE c.isremoved = :isremoved ORDER BY c.creationdate ' . $sortType);
$query->setParameter('isremoved', 0);
return $users = $query->getResult();
}
答案 1 :(得分:0)
您只能在预准备语句中绑定参数(在where
中使用)。无论如何都不需要在orderBy
中使用它,因为在该部分上不可能进行SQL注入。
使用普通PHP连接:
$sortType = ($sortType == 1) ? 'ASC' : 'DESC';
$query = $this->_em->createQuery('Select c from Entities\Comment c where c.isremoved=0 ORDER BY c.creationdate ' . $sortType);