C
C
Cat in coat2020-06-07 09:32:58
PHP
Cat in coat, 2020-06-07 09:32:58

PHP + PDO Is it possible to set a variable column in a query? Those. prepare a query with a column unknown in advance?

For example, I want to do this

$res = $pdo->prepare("UPDATE table SET :column = :value;");
$res->execute(Array(':column'=>'col1', ':value'=>'val1'));


Is that possible? Or does the column name always need to be known in advance?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanatPHP, 2020-06-07
@kostarev_v

In general, for one field, the task looks somewhat artificial, but to update several fields, you need to use the standard whitelist check

// the list of allowed field names
$allowed = ["name","surname","email"];

// initialize an array with values:
$params = [];

// initialize a string with `fieldname` = :placeholder pairs
$setStr = "";

// loop over source data array
foreach ($allowed as $key)
{
    if (isset($_POST[$key]) && $key != "id")
    {
        $setStr .= "`$key` = :$key,";
        $params[$key] = $_POST[$key];
    }
}
$setStr = rtrim($setStr, ",");

$params['id'] = $_POST['id'];
$pdo->prepare("UPDATE users SET $setStr WHERE id = :id")->execute($params);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question