简体   繁体   English

如何在mysql语法中检查用户值是否为null?

[英]How can I check user value null or not within mysql syntax?

If the user sends AGE value null then don't execute. 如果用户发送的AGE值为null,则不执行。 How do I write properly in MySQL 如何在MySQL中正确编写

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

You can use 您可以使用

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

You can also add constraints if you want only specific age groups. 如果只需要特定年龄段,也可以添加约束。 example:if you want age group between 18 and 40 示例:如果您希望年龄段在18到40之间

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

You weren't very clear in your question, so I'll provide for both PHP & mySQL: 您的问题不太清楚,因此我将同时提供PHP和mySQL:

mySQL MySQL的

Use the IS NOT NULL . 使用IS NOT NULL Reference 参考

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

PHP PHP

Use empty() or isset() . 使用empty()isset() Reference. 参考。

if(!empty($age)){
    //execute mySQL
}
SELECT
    *
FROM
    `ident`
WHERE
    FirstName = '$first_name'
    && Age != ''
    && Age = $age
    && Age IS NOT NULL;
if ($age !== null) {
$result = mysqli_query("select * from ident where FirstName = '$first_name' Age = $age");
//etc..
}

You should check this on PHP page before querying the database. 在查询数据库之前,应在PHP页面上进行检查。

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

This should be done on query building side, you might want to throw an exception if certain values are not met as expected 这应该在查询构建端完成,如果某些值未按预期满足,则可能要引发异常

PHP Use is_null() method or as said by @Huey 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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM