2013-03-07 88 views
0

在Zend Framework 2中進行數據庫查詢時,我應該如何清理用戶提交的值?例如,$下面的SQL IDZF2爲DB查詢清理變量

$this->tableGateway->adapter->query(
    "UPDATE comments SET spam_votes = spam_votes + 1 WHERE comment_id = '$id'", 
    \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE 
); 

回答

4

可以傳遞,當你執行參數..

$statement = $this->getAdapter()->query("Select * from test WHERE id = ?"); 
$result = $statement->execute(array(99)); 

$resultSet = new ResultSet; 
$resultSet->initialize($result); 

您也可以將其直接轉給查詢方法

$statement = $this->getAdapter()->query(
    "Select * from test WHERE id = ?", 
    array(99) 
); 
$result = $statement->execute(); 

$resultSet = new ResultSet; 
$resultSet->initialize($result); 

兩個將產生查詢「Select * from test WHERE id ='99'」

如果您想使用命名參數:

$statement = $this->getAdapter()->query("Select * from test WHERE id = :id"); 
$result = $statement->execute(array(
    ':id' => 99 
)); 

$resultSet = new ResultSet; 
$resultSet->initialize($result); 

如果你想你的報價表/字段名等:

$tablename = $adapter->platform->quoteIdentifier('tablename'); 

$statement = $this->getAdapter()->query("Select * from {$tablename} WHERE id = :id"); 
$result = $statement->execute(array(
    ':id' => 99 
)); 
+0

真棒,謝謝!我希望這不是愚蠢的,但該數組也可以參數化? ''select * from test WHERE id =:id「','array(':id'=> 99)'? – Wige 2013-03-07 15:09:31

+0

我相信如此:) – Andrew 2013-03-07 15:11:08

+0

更新了你的例子 – Andrew 2013-03-07 16:09:13