dongqianzong4275 2014-12-16 14:06
浏览 26
已采纳

通过mysql上的变量发送“null”不会删除该行

I have this code/query:

if ($a == $b) {
    $type = 1;
} else {
    $type = null;
}

$this->query(
    'DELETE FROM users WHERE userid = ? AND type = ?',
    array($userid, $type)
);

Buy mysql doesn't understand the second case and won't delete the row if $type is null.

I know that a proper way to define null in a query would be with IS NULL, but in my case, it won't fit.

Can I somehow pass null through a variable?

  • 写回答

2条回答 默认 最新

  • dongtun2459 2014-12-16 14:11
    关注

    It's certainly possible to make the WHERE clause itself aware switch between the value and IS NULL but requires additional conditions and additional placeholders. In your case, since the query is simple, I would build it dynamically and append parameters to the array() for execution accordingly.

    // The basic query, with conditions common to either case:
    $sql = 'DELETE FROM users WHERE userid = ? AND ';
    
    // For bound parameters...
    // $userid will always be present
    $params = array($userid);
    if ($a == $b) {
      // Add an additional parameter for type
      $params[] = 1;
      // And add to the WHERE clause the type condition
      $sql .= ' type = ?';
    }
    else
      // Or the NULL  type condition
      $sql .= 'type IS NULL';
    }
    // Execute with the $params array, which has 1 or 2 elements.
    $this->query($sql, $params);
    

    In order to stuff this into one query, the WHERE clause would have to detect that the type variable was non-null with an OR condition. One way (not the only way, and maybe not the nicest way) to do it looks like this:

    DELETE
    FROM users
    WHERE
      userid = ?
      AND ((? = 1 AND type = ?) OR type IS NULL)
    

    In this case, the value of $type would be passed in twice, first to make the condition 1=1 true, then to actually compare with the type column. But as you can see, when using placeholders, this becomes sort of confusing. It is easier to just build the string dynamically in the first place.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系