在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
);
答案 0 :(得分: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
));