0

在 Zend Framework 2 中进行数据库查询时,我应该如何清理用户提交的值?例如下面 SQL 中的 $id

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

1 回答 1

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
));
于 2013-03-07T14:58:22.457 回答