2013-03-04 53 views
1

我想將排序類型作爲參數。所以我寫了功能Doctrine2:帶參數的DQL

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(); 
} 

不過,這並不致命錯誤 未捕獲的異常「學說\ ORM \查詢\ QueryException」有消息「[語法錯誤] 0行,列77工作:錯誤:預期年底字符串,在C:\ Users \ user \ Desktop \ projects \ interview \ application \ libraries \ Doctrine \ ORM \ Query \ QueryException.php:42堆棧跟蹤:#0 C:\ Users \ user \ Desktop \ (380):Doctrine \ ORM \ Query \ QueryException :: syntaxError('line 0,col 77:...')#1 C:\ Users (745):Doctrine \ ORM \ Query \ Parser-> syntaxError('end of string')#2 C:\ Users \ Desktop \ Projects \ interview \ application \ libraries \ user \ Desktop \ projects \ interview \ application \ libraries \ Doctrine \ ORM \ Query \ Parser.php(213):Doctrin e \ 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 \ Parser-> parse()#5 C:\ Users \ user \ Deskt C:\ Users \ user \ Desktop \ projects \ interview \ application \ libraries \ Doctrine \ ORM \ Query \ QueryException.php on line 42

有沒有其他方法如何設置按參數排序類型?

回答

0

您只能在準備好的語句中綁定參數(在where中使用)。無論如何,在orderBy中都不需要使用它,因爲在該部分上不存在SQL注入的可能性。

僅有的concat使用純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); 
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(); 
}