在此 PHP 代码中防止 SQL 注入
Prevent SQL Injection In This PHP Code
我有以下写入 PostgreSQL 数据库的函数。我需要使其免受 SQL 注入的影响,但我不确定该怎么做。
从 pg_query_params
组装的查询部分是安全的(或者有人告诉我)但是通过 PHP 的字符串连接组装的查询的另一部分 .
显然容易受到注入攻击。
private function setItem($table, $id, $field, $itemId, $fieldValue){
$_1 = $itemId;
$_2 = $fieldValue;
$_3 = $field;
$_4 = $table;
$_5 = $id;
$parameters = array($_1, $_2);
// If the ID already exists, then update the name!
$sql = 'update ' . $_4 . ' set ' .$_3 . ' = where ' . $_5 . ' = ;';
/*$result = */pg_query_params($this->database, $sql, $parameters);
// Add ID and Name into table.
$sql = 'insert into ' . $_4 . '(' . $_5 . ',' . $_3 . ') select , where not exists(select 1 from ' . $_4 . ' where ' . $_5 . '=)';
$result = pg_query_params($this->database, $sql, $parameters);
return $result;
}
编辑:
How can I prevent SQL injection in PHP? 似乎没有解决我的问题。
我正在使用 PostgreSQL 并试图找到与 pg_query_params
兼容的东西
在创建要执行的查询之前,您可以使用 quote_ident() 要求数据库保护您的 table 和列名。你需要这样的东西:
<?php
$table = 'table name'; // unsafe
$column = 'column name'; // unsafe
$result = pg_query_params($connection,
'SELECT quote_ident(CAST( AS text)), quote_ident(CAST( AS text));',
array($table, $column)
);
$table = pg_fetch_result($result, 0, 0); // safe
$column = pg_fetch_result($result, 0, 1); // safe
$sql = 'INSERT INTO '.$table.'('.$column.') VALUES();';
echo $sql;
$result = pg_query_params($connection, $sql, array('foo'));
?>
我有以下写入 PostgreSQL 数据库的函数。我需要使其免受 SQL 注入的影响,但我不确定该怎么做。
从 pg_query_params
组装的查询部分是安全的(或者有人告诉我)但是通过 PHP 的字符串连接组装的查询的另一部分 .
显然容易受到注入攻击。
private function setItem($table, $id, $field, $itemId, $fieldValue){
$_1 = $itemId;
$_2 = $fieldValue;
$_3 = $field;
$_4 = $table;
$_5 = $id;
$parameters = array($_1, $_2);
// If the ID already exists, then update the name!
$sql = 'update ' . $_4 . ' set ' .$_3 . ' = where ' . $_5 . ' = ;';
/*$result = */pg_query_params($this->database, $sql, $parameters);
// Add ID and Name into table.
$sql = 'insert into ' . $_4 . '(' . $_5 . ',' . $_3 . ') select , where not exists(select 1 from ' . $_4 . ' where ' . $_5 . '=)';
$result = pg_query_params($this->database, $sql, $parameters);
return $result;
}
编辑:
How can I prevent SQL injection in PHP? 似乎没有解决我的问题。
我正在使用 PostgreSQL 并试图找到与 pg_query_params
在创建要执行的查询之前,您可以使用 quote_ident() 要求数据库保护您的 table 和列名。你需要这样的东西:
<?php
$table = 'table name'; // unsafe
$column = 'column name'; // unsafe
$result = pg_query_params($connection,
'SELECT quote_ident(CAST( AS text)), quote_ident(CAST( AS text));',
array($table, $column)
);
$table = pg_fetch_result($result, 0, 0); // safe
$column = pg_fetch_result($result, 0, 1); // safe
$sql = 'INSERT INTO '.$table.'('.$column.') VALUES();';
echo $sql;
$result = pg_query_params($connection, $sql, array('foo'));
?>