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");

2
  • Just clarify: are you worried the age column in your mySQL table will be NULL, or the PHP variable $age will be null? Commented Jan 14, 2014 at 7:06
  • possible duplicate of How do I check if a column is empty or null in mysql Commented Jan 14, 2014 at 7:08

6 Answers 6

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
    }
Sign up to request clarification or add additional context in comments.

1 Comment

I think he's asking about how to do it within a mySQL query.
0
SELECT
    *
FROM
    `ident`
WHERE
    FirstName = '$first_name'
    && Age != ''
    && Age = $age
    && Age IS NOT NULL;

Comments

0
if ($age !== null) {
$result = mysqli_query("select * from ident where FirstName = '$first_name' Age = $age");
//etc..
}

1 Comment

@user3181614 no worries.
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
}

Comments

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'");
}
?>

Comments

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");
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.