Search with null value, mysql

Asked

Viewed 114 times

1

I’m a beginner in programming and I’m trying to find something new, in this case, I have two fields that inform my research values, but I wish the research could be done even if a field is null

This is the request code

if($_SERVER['REQUEST_METHOD']=='POST'){
            $id_categoria = $_POST['id_categoria'];
            $id_sub_categoria = $_POST['id_sub_categoria'];
            $pagina = 1;
            $_SESSION['id_categoria'] = $id_categoria;
            $_SESSION['id_sub_categoria'] = $id_sub_categoria;

And in this case this is query executed

            $result_empresas = ("SELECT * FROM clientes 
                                WHERE categoria_id = '$id_categoria' AND subcategoria_id = '$id_sub_categoria' 
                                OR categoria_id = '$id_categoria' AND subcategoria_id = '$id_sub_categoria' IS NULL
                                OR subcategoria_id = '$id_sub_categoria' 
                                LIMIT $inicio, $qnt_result_pg");

Thank you to all who can help

  • Even so, I don’t understand why of it, because if it doesn’t matter if anyone is set or null, then because the filter ?

2 answers

0

Try it this way:

SELECT * FROM clientes 
WHERE (
(categoria_id = '$id_categoria' AND subcategoria_id = '$id_sub_categoria')
OR (categoria_id = '$id_categoria' AND subcategoria_id = '$id_sub_categoria' IS NULL)
OR (subcategoria_id = '$id_sub_categoria')
) 
LIMIT $inicio, $qnt_result_pg

Or:

SELECT * FROM clientes 
WHERE 
(
  (categoria_id = '$id_categoria' OR categoria_id IS NULL)
OR 
  (subcategoria_id = '$id_sub_categoria' OR subcategoria_id IS NULL)
) 
LIMIT $inicio, $qnt_result_pg

When to work with OR must always be attentive, if not the next ones hinder the previous ones.

  • it returned me, the following error, Parse error: syntax error, Unexpected 'clients' (T_STRING)

0

When writing selects with criteria this way, I recommend using parentheses to make explicit the conditions, to make a reading clearer.

I believe that’s what you need:

SELECT * 
FROM clientes 
WHERE ( categoria_id = '$id_categoria' OR '$id_categoria' IS NULL ) AND 
    ( subcategoria_id = '$id_sub_categoria' OR '$id_sub_categoria' IS NULL ) AND
    ('$id_sub_categoria' IS NOT NULL OR '$id_categoria' IS NOT NULL)
LIMIT $inicio, $qnt_result_pg"

Browser other questions tagged

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