Does pg_prepare() prepared statement (not PDO) prevent SQL-Injection?

依然范特西╮ 提交于 2019-12-01 22:15:25

A prepared statement is safe from SQL injection because nobody can change the queryplan after it's prepared. But, if your statement is already compromised, you still suffer from SQL injection:

<?php 
// how NOT to construct your SQL....
$query = 'SELECT * FROM user WHERE login=$1 and password=md5($2) LIMIT '. $_POST['limit']; -- injection!
$result = pg_prepare($dbconn, "", $query);
$result = pg_execute($dbconn, "", array($_POST["user"], $_POST["password"]));
if (pg_num_rows($result) < 1) {
  die ("failure");
}
?>

Prepared statements are built into MySQL (http://dev.mysql.com/doc/refman/5.6/en/sql-syntax-prepared-statements.html). The injection prevention mechanism is also in MySQL, see this quote from the previously linked page:

Protection against SQL injection attacks. The parameter values can contain unescaped SQL quote and delimiter characters.

PHP libraries are just mapping their functionality to MySQL functions (probably using http://docs.oracle.com/cd/E17952_01/refman-5.0-en/c-api-prepared-statement-function-overview.html). So yes, pg_prepare should also safeguard you for injection.

[EDIT] I just noticed you're talking about PostgreSQL, for PostgreSQL the same goes, it is a built in language feature, not something a PHP library provides.

As far as I could gather from the docs it should guard you against SQL injection.

A more generic approach would be to use pg_query_params as it's not connected with preparing the query.

Using prepared statements is generally the best way to go, since you should also get better SQL performance from database optimisations that can be skipped.

However it is always good to know alternative ways of doing things, so bear in mind you can use pg_escape_string() on your tainted variables and then use the outputs directly in a SQL query.

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