防止此PHP代码中的SQL注入

防止此PHP代码中的SQL注入,php,postgresql,sql-injection,Php,Postgresql,Sql Injection,我有以下函数可以写入PostgreSQL数据库。我需要确保它不受SQL注入的影响,但我不知道如何做到这一点 从pg_query_params组合的查询部分是安全的,不会被注入(或者我已经被告知),但是通过PHP的字符串连接组合的查询的另一部分显然容易被注入 private function setItem($table, $id, $field, $itemId, $fieldValue){ $_1 = $itemId; $_2 = $fieldValue; $_3 =

我有以下函数可以写入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 . ' = $2 where ' . $_5 . ' = $1;';
    /*$result = */pg_query_params($this->database, $sql, $parameters);

    // Add ID and Name into table.
    $sql = 'insert into ' . $_4 . '(' . $_5 . ',' . $_3 . ') select $1, $2 where not exists(select 1 from ' . $_4 . ' where ' . $_5 . '=$1)';

    $result = pg_query_params($this->database, $sql, $parameters);

    return $result;
}
编辑:

似乎没有解决我的问题


我正在使用PostgreSQL,并试图找到与
pg_query_params

兼容的内容。在创建要执行的查询之前,您可以要求数据库保护表名和列名。你需要这样的东西:

<?php
$table = 'table name'; // unsafe
$column = 'column name'; // unsafe
$result = pg_query_params($connection, 
  'SELECT quote_ident(CAST($1 AS text)), quote_ident(CAST($2 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($1);';

echo $sql;

$result = pg_query_params($connection, $sql, array('foo'));
?>

似乎是mysql,与
pg\u query\u参数不兼容