0

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.

2

1 Answer 1

1

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.

1
  • In my case, $fieldName is not a user input, it comes from my code. I suppose that in this case, I don't need the switch statement. I suppose there could be something to be gained by centralizing the values this can take, but it would come at the expense of readability.
    – JDelage
    Jan 31, 2012 at 22:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.