在 PDO 语句中动态更改列名

2021-12-26 00:00:00 php mysql pdo prepared-statement

是否可以在准备好的 MySQL 语句中将列名作为参数传递?举个例子:

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 在每个参数周围添加 ',所以上面的中间行变成:

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

SET 'Homepage' = '1.jpg'

MySQL 不喜欢哪个.有没有办法在 PDO 语句中包含字段名称的参数并让它们接受?

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

否则我想我将不得不编写几个不同的 PDO 语句,这取决于所选择的内容(?).

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

推荐答案

你需要做这样的事情:

$column = 'someColumn';

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

参数化占位符仅用于值.

Parameterized placeholders are only for values.

我建议您阅读@YourCommonSense 就您的问题发表的评论.

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

相关文章