Mysql search with only one of the selected fields

Asked

Viewed 37 times

0

I have a question about how to organize this information, I have two selects in my code, that the user choose both it, generates the table searching who has the two information, however I would like the search to be done even if the user selects only one of the two fields

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

I thank all who can help.

1 answer

0

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

I suppose that’s the only thing that should work if it doesn’t work with NULL, use ''.

$result_empresas = "SELECT * FROM clientes WHERE 
                   (categoria_id = '$id_categoria' OR '$id_categoria' = '') AND
                   (subcategoria_id = '$id_sub_categoria' OR '$id_sub_categoria' = '')                              
                   LIMIT $inicio, $qnt_result_pg"; 
  • It did not work in this case, if I select only one of the selects, it does not generate the table

  • Try the second way I put in the example

Browser other questions tagged

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