2014-01-14 42 views
0

如果用户发送AGE值null,则不执行。我如何在MySQL中正确编写如何在mysql语法中检查用户值是否为null?

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

+0

只是澄清:你担心你的MySQL表年龄列将是NULL,或者PHP变量'$ age'将为空? – Huey

+0

可能的重复[如何检查列是否为空或在MySQL](http://stackoverflow.com/questions/8470813/how-do-i-check-if-a-column-is-empty-或null-in-mysql) – Huey

回答

0

你不在在你的问题非常清楚,所以我将提供两个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 
} 
+0

不工作,先生! – user3181614

+0

谢谢我只是删除了现场制造麻烦! – user3181614

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

@ user3181614不用担心。 – NewInTheBusiness

0

您应该查询数据库之前,PHP网页上检查。

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

谢谢你Tashi Delek! – user3181614

0

这应该在查询建设方来完成,你可能要抛出一个异常,如果某些值不被@Huey

满足预期

PHP 使用is_null()方法或者说

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

谢谢。扎西德勒克! – user3181614

5

您可以使用

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

如果只需要特定的年龄段,还可以添加约束条件。 例如:如果你想年龄介乎18岁至40

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

我想他是问如何在mySQL查询中做到这一点。 – Huey

相关问题