Set variable to null in a Query in php

Asked

Viewed 289 times

0

I have the following QUERY on my system:

$Query = "SELECT * FROM Monit WHERE
    ($Modulo IS NULL OR Modulo = '$Modulo') AND 
    ($Usuario IS NULL OR Usuario = '$Usuario') AND
    ($Data IS NULL OR Data_reg = '$Data') 
    ORDER BY Data_monit DESC LIMIT 0,10";
    $execute = mysqli_query($conexao, $Query);

    while($line = mysqli_fetch_array($execute)){
        echo $line['Modulo'];
    }

To test whether it would work when some value entered NULL defined the variables with these values:

$Modulo = "NULL";
$Usuario = "NULL";
$Data = "NULL";

And it works perfectly this way. However, if I define the entries in this way:

$Modulo = "NULL";
$Usuario = "roberto";
$Data = "NULL";

It doesn’t work because the single quotes are missing ' ' I put it that way:

$Modulo = "NULL";
$Usuario = "'roberto'";
$Data = "NULL"; 

The query does not work, and if I add the simple quotes directly in the query:

$Query = "SELECT * FROM Monit WHERE
    ($Modulo IS NULL OR Modulo = '$Modulo') AND 
    ('$Usuario' IS NULL OR Usuario = '$Usuario') AND
    ($Data IS NULL OR Data_reg = '$Data') 
    ORDER BY Data_monit DESC LIMIT 0,10";
    $execute = mysqli_query($conexao, $Query);

    while($line = mysqli_fetch_array($execute)){
        echo $line['Modulo'];
    }

It will work, however, if you return the NULL value in the variables will not return anything; I don’t know if it was very clear, but basically I don’t know how to define the variables that will be in the query as null.

1 answer

1


I do not know if it is a very elegant solution but you can validate if the variable is filled before mounting the query and maintain the single quotes:

if($Modulo == NULL) $Modulo = '';
if($Usuario == NULL) $Usuario = '';
if($Data == NULL) $Data = '';

$Query = "SELECT * FROM Monit WHERE
    ($Modulo = '' OR Modulo = '$Modulo') AND 
    ($Usuario = '' OR Usuario = '$Usuario') AND
    ($Data = '' OR Data_reg = '$Data') 
    ORDER BY Data_monit DESC LIMIT 0,10";
    $execute = mysqli_query($conexao, $Query);
  • So I keep simple quotes on variables before IS NULL?

  • Sorry, @Shinchila_matadora, removed; see if you’ve solved

  • 2

    Thanks @rLinhares, I only had to put the quotes in the variables but the logic worked :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.