ZF2 sanitize variables for DB queries

被刻印的时光 ゝ 提交于 2019-12-23 04:43:48

问题


In making database queries in Zend Framework 2, how should I be sanitizing user submitted values? For example, $id in the following SQL

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

回答1:


You can pass parameters when you execute..

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

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

You can also pass them directly to the query method

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

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

Both will produce the query "Select * from test WHERE id = '99'"

If you want to use named parameters:

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

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

If you want to quote your table/field names etc:

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

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


来源:https://stackoverflow.com/questions/15274354/zf2-sanitize-variables-for-db-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!