I have the following function that writes into a PostgreSQL database. I need to make it safe from SQL injection however I am not sure how to do that.
The part of the query assembled from pg_query_params
is safe from injection (or so I have been told) however the other part of the assembled query via PHP's string concatenation .
is apparently vulnerable to injection.
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;
}
Edit:
How can I prevent SQL injection in PHP? doesn't seem to address my concern.
I am using PostgreSQL and trying to find something compatible with pg_query_params
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…