I’m curious why this code works fine:
function updateRecord($idFieldName, $recordID, $fieldName, $recordValue){
$dbConnection=$this->dbConnect();
$updated=false;
while (!$updated){
$query=$dbConnection->prepare("UPDATE $this->table SET $fieldName = :recordValue WHERE $idFieldName = :recordID");
$query->bindParam(":recordValue", $recordValue);
$query->bindParam(":recordID", $recordID);
$updated=$query->execute();
}
}
Whereas this one doesn’t:
function updateRecord($idFieldName, $recordID, $fieldName, $recordValue){
$dbConnection=$this->dbConnect();
$updated=false;
while (!$updated){
$query=$dbConnection->prepare("UPDATE $this->table SET :fieldName = :recordValue WHERE $idFieldName = :recordID");
$query->bindParam(":fieldName", $fieldName);
$query->bindParam(":recordValue", $recordValue);
$query->bindParam(":recordID", $recordID);
$updated=$query->execute();
}
}
I don’t understand what parameters can be bound outside the query statement, and which ones have to be included directly into the statement.
You can’t use dynamic column names as data parameters in PDO (nor in any other PHP SQL library AFAIK).
You’ll have to insert the column name directly into the string. To avoid SQL injection, you should compare the column name against a list of existing valid column names.