代码之家  ›  专栏  ›  技术社区  ›  Lev Buchel

跳过特定变量的sql execute,以防它在php中为null

  •  0
  • Lev Buchel  · 技术社区  · 6 年前

    function configurationSet(int $id, string $name, string $last=null) {
        $s = pdo()->prepare("update myTable set nameCol = ?, lastCol = ? where id = ?");
        $s->execute([$name, $last, $id]);
    }
    

    我不想在此函数中使用“if”语句或创建新函数

    $last==null $last 变量,因此它在默认情况下设置为null),执行将不会更新 $最后 null

    要说清楚的是,在 firstCol lastCol 拉斯特科尔 万一是的话 无效的 (只需更新 ).

    谢谢你的帮助!

    1 回复  |  直到 6 年前
        1
  •  0
  •   Lev Buchel    6 年前

    这是我设法找到的解决办法

    function configurationSet(int $id, string $name, string $last=null) {
       $s = pdo()->prepare("update myTable set nameCol = ?, lastCol = CASE WHEN ? is null THEN lastCol ELSE ? END where id = ?");
       $s->execute([$name, $last, $last, $id]);
    }
    

    “什么时候?那么脚本是否为null?“结束”