Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change column name in PDO statement [duplicate]

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(?).

like image 318
Chuck Le Butt Avatar asked Feb 16 '23 08:02

Chuck Le Butt


1 Answers

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.

like image 53
Phil Cross Avatar answered Apr 12 '23 23:04

Phil Cross