假设我有一个常规的准备语句,但有时我必须省略一些更新的列:
$stmt = $db->prepare("UPDATE table SET price = ?, size = ?, color = ?
WHERE id = ? LIMIT 1");`
大多数情况下执行会是这样的:
$stmt->execute([ $price, $size, $color, $id ]);
但在某些情况下,我必须省略一些被更改的列。
例如:
if( $size == 0 ) {
// in this case I must omit the size column and keep the current value
///in the database. I don't need the zero in there
}
有什么聪明的方法可以包含/删除查询的列吗?
根据您在任何特定时间想要执行的操作动态构建查询
if ( $IdontneedSize ) {
$stmt = $db->prepare("UPDATE table
SET price = ?, color = ?
WHERE id = ? LIMIT 1");
$stmt->execute([ $price, $color, $id ]);
} else {
$stmt = $db->prepare("UPDATE table
SET price = ?, size = ?, color = ?
WHERE id = ? LIMIT 1");
$stmt->execute([ $price, $size, $color, $id ]);
}
它不需要比这更复杂。
回复您的评论。你的意思是这样的吗?
你可以先做好所有准备工作,给它们起个好听的名字
$NoSize = $db->prepare("UPDATE table
SET price = ?, color = ? WHERE id = ? LIMIT 1");
$allThree= $db->prepare("UPDATE table
SET price = ?, size = ?, color = ? WHERE id = ? LIMIT 1");
if ( $size = 0 ) {
$NoSize->execute([ $price, $color, $id ]);
} else {
$allThree->execute([ $price, $size, $color, $id ]);
}
但是,如果您从未真正使用过 NoSize senario,那么您就浪费了服务器往返时间来编译和优化您永远不会使用的查询。