0

If the user sends AGE value null then don't execute. How do I write properly in MySQL

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

sas
  • 2,563
  • 1
  • 20
  • 28
user3181614
  • 145
  • 8
  • Just clarify: are you worried the age column in your mySQL table will be NULL, or the PHP variable `$age` will be null? – Huey Jan 14 '14 at 07:06
  • possible duplicate of [How do I check if a column is empty or null in mysql](http://stackoverflow.com/questions/8470813/how-do-i-check-if-a-column-is-empty-or-null-in-mysql) – Huey Jan 14 '14 at 07:08

6 Answers6

5

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

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

You weren't very clear in your question, so I'll provide for both PHP & mySQL:

mySQL

Use the IS NOT NULL. Reference

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

PHP

Use empty() or isset(). Reference.

if(!empty($age)){
    //execute mySQL
}
Huey
  • 5,110
  • 6
  • 32
  • 44
0
SELECT
    *
FROM
    `ident`
WHERE
    FirstName = '$first_name'
    && Age != ''
    && Age = $age
    && Age IS NOT NULL;
Peon
  • 7,902
  • 7
  • 59
  • 100
0
if ($age !== null) {
$result = mysqli_query("select * from ident where FirstName = '$first_name' Age = $age");
//etc..
}
NewInTheBusiness
  • 1,465
  • 1
  • 9
  • 14
0

You should check this on PHP page before querying the database.

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

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

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