我有以下数据
$field = 'f1','f2','f3'; // (comma separated string)
$value = 'v1','v2','v3'; // (comma separated string)
Run Code Online (Sandbox Code Playgroud)
是否有任何快捷方式可以生成这样的更新查询。
UPDATE table set ($field = $value) where id =1;
Run Code Online (Sandbox Code Playgroud)
此方法适用于插入查询,但我不知道如何使用这种更新查询。
我认为处理此类问题的最佳方法是将数据存储在关联数组中,而不是像以前使用的字符串中那样存储:
$data = array(
'f1' => 'v1',
'f2' => 'v2',
'f3' => 'v3'
);
// Then for an insert:
$query = "INSERT INTO table (`".implode("`, `", array_keys($data))."`) VALUES ('".implode("', '", array_values($data))."')";
// And an update
$updates = array();
foreach ($data as $key => val) $updates[] = "`$key` = '$val'";
$query = "UPDATE table SET ".implode(', ',$updates)." WHERE `id` = 1";
// Or even a select
$where = array();
foreach ($data as $key => val) $where[] = "`$key` = '$val'";
$query = "SELECT * FROM table WHERE ".implode(' AND ',$where);
Run Code Online (Sandbox Code Playgroud)
如果这样做,则需要确保在构建阵列时转义数据。或者更好的是,使用准备好的语句。