Dynamically change column name in PDO statement [d

2020-02-06 03:49发布

问题:

Is it possible pass a column name as parameter in a prepared MySQL statement? Take the following example:

UPDATE Images
SET :placement = :imageURL
WHERE ID = :titleID;

PDO adds ' around each parameter, so the middle line above becomes:

SET 'Homepage' = '1.jpg'

Which MySQL doesn't like. Is there a way to include parameters for fieldnames in PDO statements and have them accepted?

Otherwise I guess I'll have to write several different PDO statements, depending on what's been chosen(?).

回答1:

You would need to do something like this:

$column = 'someColumn';

$stmt = $db->prepare("UPDATE tableName SET {$column} = :columnValue WHERE ID = :recordId");

Parameterized placeholders are only for values.

I would suggest you read the comment @YourCommonSense posted on your question.



回答2:

In situations such as this, I use a different sort of replacement parameters, like so:

$unitLabel = 'store_number';
$sql = 'select * from users where [unitLabel] = :unit and level = :level;';
$sql = str_replace('[unitLabel]', $unitLabel, $sql);
$params = array(
  ':unit' => 300,
  ':level' => 'admin',
);
$stmt = $dbh->prepare($sql);
$stmt->execute($params);

The prepared SQL query ends up being processed (more or less) as:

SELECT * FROM USERS WHERE store_number = 300 AND level = 'admin';

Which works for my situation. I hope this helps. :)