I'm not sure why this is failing, I have two examples, they are the same function, but one works and the other doesn't work. I really want the one that doesn't work to work, because it will allow me to put a lot of my potentially repetitive code into a single function.
This calls either setItemWorks
or setItemDoesNotWork
.
public function setitemName($itemId, $name){
/* Add the name of the item to the database */
$fieldName = 'name';
$tableName = "items";
$idName = "id";
$result = $this->setItemWorks($itemId, $name);
// Use comments to enable below function and disable function call above.
//$result = $this->setItemDoesNotWork($tableName, $idName, $fieldName, $itemId, $name);
}
setItemDoesNotWork:
private function setItemDoesNotWork($table, $id, $field, $itemId, $fieldValue){
$_1 = $itemId;
$_2 = $fieldValue;
$_3 = $field;
$_4 = $table;
$_5 = $id;
$parameters = array($_1, $_2, $_3, $_4, $_5);
// If the ID already exists, then update the name!
$sql = 'update $4 set $3 = $2 where $5 = $1;';
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;
}
setItemWorks:
private function setItemWorks($table, $id, $field, $itemId, $fieldValue){
$_1 = $itemId;
$_2 = $fieldValue;
$parameters = array($_1, $_2);
// If the ID already exists, then update the name!
$sql = 'update items set $name = $2 where id = $1;';
pg_query_params($this->database, $sql, $parameters);
// Add ID and Name into table.
$sql = 'insert into items(id, name) select $1, $2 where not exists(select 1 from items where id=$1)';
$result = pg_query_params($this->database, $sql, $parameters);
return $result;
}
It seems that when I try putting 5 variables into the pg_query_params
it doesn't work.
This is the error I am getting:
Error:
[20-Mar-2015 00:17:19 UTC] PHP Warning: pg_query_params(): Query failed: ERROR: syntax error at or near "$4"
LINE 1: update $4 set $3 = $2 where $5 = $1;
^ in /home/ubuntu/workspace/lib/ItemDatabase.php on line 139
Edit: The current answer I have put down is unsafe, any ideas how to make this safe whilst not being able to use pg_query_params
?