使用PDO更新未知值的未知字段?

时间:2013-12-31 11:30:25

标签: php mysql arrays pdo

我正在尝试将记录更新到我的表中,我提前不知道将要更新的字段,将更新的字段数或这些字段将保留的值 - 其中一些将被设置为空。

我已经选择记录事先记录的内容和更改后的记录之间的变化,而不是简单地更新整个记录(考虑到任何时候只有一个字段可能会发生变化,这样做似乎毫无意义)。

这些记录的更改保存在我的$changes数组中,其中键是字段名称,值是字段需要保存的新值。我已经尝试使用问号表示来记录未知值,但仅此一项不能解释可能更新的字段数的差异,而且,我只看到这种符号用于选择查询。

这是我到目前为止所得到的:

$dbh->prepare("UPDATE `missions` SET ??? WHERE `mission_id`=:mission_id");
$dbh->bindParam(':mission_id', $mission_id); // Mission ID is constant and WILL NOT change

我知道我可以简单地循环我的数组来绑定参数,但我不知道如何将我的数组更改的值转换为问号所需的符号。思想和想法?

1 个答案:

答案 0 :(得分:2)

你需要对此进行一些实验,但这应该让你非常接近:

// Unknown name and number of changes
$changes = array(
    'col1' => 'first',
    'col4' => 'fourth',
    'col7' => 'seventh',
);

$setSql = array();

// Create named params, nicer than positional params
foreach ($changes as $column => $value) {
    $setSql[] = "`{$column}` = :{$column}";
}

// Use implode to create the 'set' string
$setString = implode(', ', $setSql);
var_dump($setString);
// string(46) "`col1` = :col1, `col4` = :col4, `col7` = :col7"

// Add the mission_id to the end of the changes array
$changes['mission_id'] = 1234;

$sql = sprintf('UPDATE `missions` SET %s WHERE `mission_id` = :mission_id', $setString);
var_dump($sql);
// string(101) "UPDATE `missions` SET `col1` = :col1, `col4` = :col4, `col7` = :col7 WHERE `mission_id` = :mission_id"

$stmt = $dbh->prepare($sql);
$stmt->execute($changes);
相关问题