代码之家  ›  专栏  ›  技术社区  ›  Dipak

将NULL传递给php mysql where子句

  •  -1
  • Dipak  · 技术社区  · 6 年前

    表中的一列已设置为 NULL 现在,如果用户输入是 无效的 然后选择包含 null . 如果输入为非空,则相应地选择。

    WHERE student.section = NULL // tried like '', 'NULL'
    

    但我发现这不是一个有效的方法

    所以我做了下面的逻辑,但是我觉得它结构不好,我觉得可以缩短,防止代码重复。

    如果 section 为空

    if(empty($_POST['section'])){
        $result=$con->prepare(
            "SELECT
            ...
            FROM student
            WHERE student.class=:cid AND student.section IS NULL"
        )
        $result->bindParam(':cid',$_POST['class']);
        $result->execute();
    } else {
        $result=$con->prepare(
            "SELECT
            ...
            FROM student
            WHERE student.class=:cid AND student.section=:sid"
        )
        $result->bindParam(':cid',$_POST['class']);
        $result->bindParam(':sid',$_POST['section']);
        $result->execute();
    }
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   ArtisticPhoenix    6 年前

    删除表的用法。如果没有连接,则不需要再次将其放入,这将使其“更短”,但保持相同的逻辑。

    SELECT
        ...
        FROM student
        WHERE class=:cid AND section=:sid
    

    我给你省了14次按键和 0<14 所以它是“减少的”。

    IS NOT NULL 但从逻辑上讲

      AND student.section=:sid
    

    以及

      AND student.section IS NOT NULL
    

    如果 student.section = 10 :sid 如果是20,你就得不到唱片,但如果你改成 不为空 那你会的因为 10

    更新

    $sql = 'SELECT
        ...
        FROM student
        WHERE class=:cid AND section';
    
    if(empty($_POST['section']))
        $sql .= ' IS NULL';
    else
        $sql .= ' = :sid';
    
    $result=$con->prepare($sql);
    $result->bindParam(':cid',$_POST['class']); //this is wrong
    $result->execute();
    

    更新1

    $result=$con->prepare($sql); //this is PDOStatment not a result
    $result->bindParam(':cid',$_POST['class']); //this is wrong
    $result->execute(); //your not setting a result variable
    

    同时,它也很难有条件地绑定到 stmt (PDOStatment object) 因为在构造查询时还没有。你能做到的 prepare cid 你可以做条件2,然后在第二个条件下绑定。但是,我们正在缩短它,幸运的是,我们可以将参数作为 execute .

    所以我要把它改成使用一个参数数组

    $sql = 'SELECT
        ...
        FROM student
        WHERE class=:cid AND section';
    
    $param = [':cid' => $_POST['class']];
    
    if(empty($_POST['section'])){
        $sql .= ' IS NULL';
    }else{
        $sql .= ' = :sid';
        $param[':sid'] = $_POST['section'];
    }
    
    $stmt=$con->prepare($sql);
    $result = $stmt->execute($param);
    
    $data = $result->fetchAll(PDO::FETCH_ALL);
    

    $result 问题。

        2
  •  0
  •   marcogmonteiro    6 年前

    选择空值时,不应使用equal语句。您应该使用IS语句,例如:

    SELECT foo
    FROM bar
    WHERE status IS NULL;
    

    或非空值

    SELECT foo
    FROM bar 
    WHERE status IS NOT NULL;