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.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
JDelage
  • 13,036
  • 23
  • 78
  • 112
  • What happens or doesn't happen? At which point does which code fail how? – Pekka Jan 31 '12 at 22:19
  • possible duplicate of [Can PHP PDO Statements accept the table name as parameter?](http://stackoverflow.com/questions/182287/can-php-pdo-statements-accept-the-table-name-as-parameter) – Pekka Jan 31 '12 at 22:21

1 Answers1

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.

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • 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 '12 at 22:32