Character "wildcard" as criterion of a query

1

I'm trying to create a query criteria selection engine. For example:

I have a mass of data where you have the following variables:

  • store code
  • Brazilian state where you are
  • Brazilian region you are in
  • Flag of products that the store distributes
  • date of sale
  • value
  • The field I want to return is value field, provided one or more of the above criteria has been satisfied. I did not want to create all the varieties of possible combinations between these 5 fields. So I wanted to know:

    Can wildcard characters (type *) be used as query criteria?

    Then I could define the variables as follows:

    if(isset($_GET['uf'])){ // Estado brasileiro
        $uf = $_GET['uf'];
    } else {
        $uf = "*"; 
    }
    if(isset($_GET['rg'])){ // Região brasileira
        $rg = $_GET['rg'];
    } else {
        $rg = ""; 
    }
    
    if(isset($_GET['ini']) && $_GET['fim'] ){ // data incicial
        $ini = $_GET['ini'];
    } else {
        $ini = "01/01/2017"; 
        $fim = date("d-m-Y");
    }
    if(isset($_GET['band'])){ // bandeira
        $band = $_GET['band'];
    } else {
        $band = "*"; 
    }
    

    And then mount a single query that can meet any criteria set or not:

    $qry = "SELECT sjy_grupo.id_grupo, sjy_empresas.bandeira AS id_bandeira, sjy_bandeira.bandeira
            FROM sjy_bandeira INNER JOIN 
                 sjy_grupo INNER JOIN sjy_empresas ON sjy_grupo.id_grupo = sjy_empresas.grupo
            AND sjy_bandeira.id_bandeira = sjy_empresas.bandeira
            WHERE id_grupo = '$grupo'
            AND id_bandeira = '$id_bandeira'
            GROUP BY sjy_grupo.id_grupo, sjy_bandeira.id_bandeira, sjy_bandeira.bandeira";
    
        
    asked by anonymous 05.09.2017 / 14:17

    1 answer

    1

    The wildcard character exists and is "%" . It should be used in conjunction with the LIKE word instead of the equal sign ( = ) (as noted in comment.

    That said, I point out that it would be bad to use wildcard characters in this type of query. That's because if you happen to need to use a wildcard character on purpose, you're going to have a problem. Another reason is that it can bring accidentally unwanted values.

    In my view, it is better to check for value in these variables.

    $qry = "SELECT sjy_grupo.id_grupo, sjy_empresas.bandeira AS id_bandeira, sjy_bandeira.bandeira
        FROM sjy_bandeira INNER JOIN 
             sjy_grupo INNER JOIN sjy_empresas ON sjy_grupo.id_grupo = sjy_empresas.grupo
        AND sjy_bandeira.id_bandeira = sjy_empresas.bandeira";
    
    if (isset($grupo)) {
        $qry .= " WHERE id_grupo = '$grupo'";
    }
    
    if (isset($id_bandeira)){
        $qry .= " AND id_bandeira = '$id_bandeira'";
    }
    
    $qry .= " GROUP BY sjy_grupo.id_grupo, sjy_bandeira.id_bandeira, sjy_bandeira.bandeira";
    
        
    06.09.2017 / 14:01