Recover Larger ID in Database query

Asked

Viewed 56 times

0

all right?

I’m working on a client website, which was developed using codeigniter. The tables created by the programmer were not designed for some functions, and the client requested that I create them.

I have a table of services, and a history of services, and each time a service is updated, this table receives a new record linked to the service performed. I would need to return the last historical ID linked to the service in question. And I would like to know how I can do this.

For better understanding, here is other information.

Table of Services

Tabela de Serviços

History of Services

Tabela de Histórico de Serviços

The Service History table, has in the column "id_servico", the identification of the service that is linked to the other table. I need to return from the history table, the most recent ID linked to the service in question. In this case of the above example, it should return the Ids "1002" and "1004", but it is returning the "1000" and the "1003".

This is the code I’m using to list:

Function in the Model

function busca_historico() {
        $this->db->order_by($this->id, 'DESC');
        $this->db->group_by('id_servico');
        $query = $this->db->get($this->tabela);
        if ($query->num_rows() > 0) {
            return $query->result();
        } else {
            return false;
        }
    }

Function in the Controller

function teste(){

        $data['servico'] = $this->servicos_model->get_result();
        $data['historico'] = $this->historico_servicos->get_historico();

        $this->load->view('teste/teste', $data);

    }

Code in the View

    <?php foreach($historico as $val) : ?>

        <?php if($val->status == 'Concluído') : ?>

             <?= $val->id; ?>

             <br />

        <?php endif; ?>

   <?php endforeach; ?>

Well, that’s it. I don’t know what I need to make it work. If you can help me, I’d appreciate it.

  • if the ID value is sequential, and since I didn’t see a date field in your table, you can get the largest ID (select max(ID) where id_servico=533), I used 533 as an example

  • There is a "date" field in the table, but it is formatted as CHAR and this ended up complicating me. Then I got this problem. I know there are ways around this, but all the ones I found involve executing queries right on the table to then convert from CHAR to DATE, and as there is the risk of zeroing the column data, I’m trying to find an alternative way. I’ll try your tip.

No answers

Browser other questions tagged

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