【问题标题】:How can I check user value null or not within mysql syntax?如何在 mysql 语法中检查用户值是否为空?
【发布时间】:2014-02-02 03:54:50
【问题描述】:

如果用户发送 AGE 值为 null 则不执行。如何在 MySQL 中正确写入

$result = mysqli_query("select * from ident where FirstName = '$first_name' && $age != '' && Age = $age");

【问题讨论】:

标签: php mysql


【解决方案1】:

你可以使用

    if(!empty($age)){
    //do sql operation
    }

如果您只需要特定年龄组,也可以添加限制条件。 示例:如果您想要 18 到 40 岁之间的年龄组

    if ($_POST["age"] < 18 || $_POST["age"] > 40){
     //print error message
    }
    else{
     //do sql operation
    }

【讨论】:

  • 我认为他是在询问如何在 mySQL 查询中执行此操作。
【解决方案2】:
SELECT
    *
FROM
    `ident`
WHERE
    FirstName = '$first_name'
    && Age != ''
    && Age = $age
    && Age IS NOT NULL;

【讨论】:

    【解决方案3】:
    if ($age !== null) {
    $result = mysqli_query("select * from ident where FirstName = '$first_name' Age = $age");
    //etc..
    }
    

    【讨论】:

    • @user3181614 不用担心。
    【解决方案4】:

    你的问题不是很清楚,所以我会同时提供 PHP 和 mySQL:

    mySQL

    使用IS NOT NULLReference

    SELECT * FROM ident 
        WHERE FirstName = '$first_name' 
        AND Age IS NOT NULL 
        AND Age = $age
    

    PHP

    使用empty()isset()Reference.

    if(!empty($age)){
        //execute mySQL
    }
    

    【讨论】:

      【解决方案5】:

      您应该在查询数据库之前在 PHP 页面上检查这一点。

      <?php
      if(!empty($age)) {
          $result = mysqli_query("select * from ident where FirstName = '$first_name' AND Age = '$age'");
      }
      ?>
      

      【讨论】:

        【解决方案6】:

        这应该在查询构建方面完成,如果某些值未按预期满足,您可能希望抛出异常

        PHP 使用is_null() 方法或@Huey 所说的

        if(isset($age) and !is_null($age) and intval($age) > 0){
            $result = mysqli_query("SELECT * FROM ident WHERE FirstName = '$first_name' AND Age = $age");
        }
        

        【讨论】:

          猜你喜欢
          • 2021-08-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-02-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多