Dynamically changing a column name in a PDO statement

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

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

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

 SET 'Homepage' = '1.jpg' 

Which MySQL do not like. Is there a way to include parameters for field names in PDO declarations and accept them?

Otherwise, I think I will have to write several different PDO instructions, depending on what was selected (?).

+4
source share
2 answers

You will need to do something like this:

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

Parameterized placeholders are for values ​​only.

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

+8
source

In such situations, I use different replacement options, for example:

 $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 finished SQL query ends with processing (more or less) as follows:

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

What works for my situation. Hope this helps. :)

0
source

Source: https://habr.com/ru/post/1484056/


All Articles