Dynamically change column name in PDO statement [duplicate]

心已入冬 提交于 2019-12-17 20:01:59

问题


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. :)



来源:https://stackoverflow.com/questions/16885091/dynamically-change-column-name-in-pdo-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!