Search field/data filter

Asked

Viewed 855 times

0

Hello, I’m developing a field of data research. And this, is working very well so far; but I would like to add some query parameters to this field.

As it is today (search possibilities):
Data inicial Data final Nome.

As I wish:
Data inicial Data final Opção que filtra todos os estoque (abaixo e acima do minimo), outra opção que filtra somente abaixo do estoque minimo e uma ultima opção que filtra somente acima do estoque minimo. Pesquisar pelo id, nome ou descricao (três colunas diferentes) em um só campo.

Note: There are two fields for the products table, related to stock, these being, stock and stocking_min. I want to make a query, using a select, which, depending on the selected option, bring the queries if the stock is larger, smaller than stock_min or all.

I am using the GET method to perform this query:
Follow code from view:

<form method="get" action="<?= base_url()?>admin/produtos">
    <div class="modal-body">
        <div class="row">                               
            <div class="form-group col-sm-6">
                <label for="dt_inicio">Cadastro inicial</label>
                <div class="input-group">
                    <div class="input-group-addon">
                        <i class="fa fa-calendar"></i>
                    </div>
                    <input type="text" name="de" class="form-control pull-right" id="datepicker" autocomplete="off" value="<?php echo $this->input->get('de'); ?>">
                </div>
            </div>
            <div class="form-group col-sm-6">
                <label for="dt_fim">Cadastro final</label>                                  
                    <div class="input-group">
                        <div class="input-group-addon">
                            <i class="fa fa-calendar"></i>
                        </div>
                    <input type="text" name="ate" class="form-control pull-right" id="datepicker2" autocomplete="off" value="<?php echo $this->input->get('ate'); ?>">
                </div>
            </div>                              
        </div>                      
        <div class="form-group">                                
            <label for="estoque" class="control-label">Estoque</label>
                <select name="estoque" class="form-control">
                    <option value="" selected="selected">Todos</option>
                    <option value="1">Acima do estoque mínimo</option>
                    <option value="2">Abaixo do estoque mínimo</option>
                </select>
            </div>                          
            <div class="form-group">
                <label for="produto">Produto</label>
                <input type="text" id="pesquisar_dados" name="pesquisar_dados" class="form-control" autocomplete="off" value="<?php echo $this->input->get('pesquisar_dados'); ?>" placeholder="Pesquise nome do produto" autofocus="autofocus">                                
            </div>                      
        </div>
        <div class="modal-footer clearfix">
            <button type="button" class="btn btn-default btn-flat" data-dismiss="modal"><i class="fa fa-times"></i> Cancelar</button>
            <button type="submit" class="btn btn-primary btn-flat pull-left"><i class="fa fa-search"></i> Pesquisar</button>
        </div>
</form>

Follows model code:

    public function pesquisar($pesquisar, $de, $ate){

    if($pesquisar != null){
        //$this->db->or_like('id' ,$pesquisar);
        $this->db->or_like('nome' ,$pesquisar);
    }

    if($de != null){
        $this->db->where('dt_cadastro >=' ,$de);
        $this->db->where('dt_cadastro <=', $ate);
    }
    $this->db->limit(10);
    return $this->db->get('produtos')->result();
}

Segue Controller:

$de = $this->input->get('de');
$ate = $this->input->get('ate');
$estoque = $this->input->get('estoque');
$pesquisar = $this->input->get('pesquisar_dados');

    if($pesquisar == null && $estoque == null && $de == null && $ate == null)
{ "exibe todos os resultados"}
else
[![inserir a descrição da imagem aqui][1]][1]{
     if($de != null){

            $de = explode('/', $de);
            $de = $de[2].'-'.$de[1].'-'.$de[0];

            if($ate != null){
                $ate = explode('/', $ate);
                $ate = $ate[2].'-'.$ate[1].'-'.$ate[0]; 
            }
            else{
                $ate = $de;
            }
        }
        $this->data['pagination'] = $this->pagination->create_links();
        $this->data['produtos'] = $this->Produtos_model->pesquisar($pesquisar, $de, $ate);
}

Table:
id` INT(11) NOT NULL AUTO_INCREMENT, `nome` VARCHAR(40) NOT NULL, `descricao` VARCHAR(80) NOT NULL, `preco_compra` DECIMAL(10,2) NULL DEFAULT NULL, `preco_venda` DECIMAL(10,2) NOT NULL, `estoque` INT(11) NOT NULL, `estoque_min` INT(11) NULL DEFAULT NULL, `usuario_cadastro` VARCHAR(40) NOT NULL, `usuario_alteracao` VARCHAR(40) NOT NULL, `dt_cadastro` DATETIME NOT NULL, `dt_alteracao` DATETIME NULL DEFAULT NULL,

inserir a descrição da imagem aqui

  • estoque and estoque_min are tables or fields of the table?

  • 1

    fields of the products table, I will edit the question, I missed...

1 answer

1


As for security, it’s good to take into account what the developer says: Escaping Queries. So I recommend adopting this here:

$de = $this->db->escape_str($this->input->get('de'));
$ate = $this->db->escape_str($this->input->get('ate'));
$estoque = $this->db->escape_str($this->input->get('estoque'));
$pesquisar = $this->db->escape_str($this->input->get('pesquisar_dados'));

Correct way to use base_url():

<form method="get" action="<?= base_url('admin/produtos')?>">

As to the model, just use the die passed by select, as it is already doing with the other fields:

public function pesquisar($pesquisar = NULL, $de = NULL, $ate = NULL, $estoque = NULL){
    if($pesquisar != NULL){
        $this->db->or_like('nome' , $pesquisar);
    }
    if($de != NULL){
        $this->db->where('dt_cadastro >=' ,$de);
        $this->db->where('dt_cadastro <=', $ate);
    }
    if($estoque != NULL){
        if($estoque == 1){$where = "estoque > estoque_min";} 
        else {$where = "estoque < estoque_min";}
        $this->db->where($where);
    }
    $this->db->limit(10);
    return $this->db->get('produtos')->result();
}

Calling for:

$this->data['produtos'] = $this->Produtos_model->pesquisar($pesquisar, $de, $ate, $estoque);

Source: Looking for Specific Data (4.Custom string)

  • Thanks for the answer. The select question worked for me. When I put base_url as you posted it, it didn’t work. Another point is, I didn’t see how to query 3 different columns in one field. id, name or description (only in the search field). This is possible?

  • Pro base_url() fail must have something wrong with your setup. If that system is in production, recommend revision urgently. The consultation in several fields in the same condition should be possible with $this->db->or_like() (that you are already using), as described here: Looking for Similar Data.

  • Checking on base_url. Now about or_like, it even works, but then the query ignores the parameter start and end date.

  • Does not proceed. The date search is ignored only if you pass a value NULL for $de. Remember: to use OR, before you have to have a LIKE: $this->db->like('nome', $pesquisar); and then $this->db->or_like('descricao', $pesquisar);, which will generate: // WHERE nome LIKE '%search%' ESCAPE '!' OR descricao LIKE '%search%' ESCAPE '!'.

  • I only have one product registered in the period from yesterday until today. Product ID is equal to 2. See my query parameter: Data Incial = 05/01/2017, Data Final = 07/01/2017. Estoque = Todos. Pesquisa = 1 SELECT * FROM productsWHEREidLIKE '%1%' ESCAPE '!' ORnameLIKE '%1%' ESCAPE '!' ANDdt_register>= '2017-01-05' ANDdt_register <= '2017-01-07' LIMIT 10 .

  • if($pesquisar != NULL){&#xA;$this->db->like('id' ,$pesquisar);&#xA;$this->db->or_like('nome' ,$pesquisar);&#xA;}

  • You are deliberately seeking id LIKE '%1%' . How do you expect the program to return id = 2? :D

Show 3 more comments

Browser other questions tagged

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