DISTINCT and GROUP BY do not work on Codeigniter

Asked

Viewed 147 times

0

everything jewel?

Recently I took a job to do, and the requester was needing to list some data on a table. I was going to ask all the questions here, but I decided to divide them into parts because it would be easier to understand for me and other people who have the same doubt.

For this case, I’m having problems performing a SELECT with DISTINCT or GROUP BY in Mysql with Codeigniter.

I’m trying to group some dates together to display a single record, and I’m not getting it done.

The result is this image:

Tabela com Datas

Below I leave the code I used.

Model

function get_datas() {

    $this->db->order_by($this->id, 'DESC');
    $this->db->group_by('data_registro');
    $this->db->from($this->tabela);

    $query = $this->db->get();

    if ($query->num_rows() > 0) {
        return $query->result();
    } else {
        return false;
    }
}

Controller:

public function index() {

    $data = array(
        'show_clientes' => $this->mdl_clientes->get_datas(),
    );

    $flash_msg = $this->session->flashdata('flash_message');
    if (isset($flash_msg) && !empty($flash_msg)) {
        $data['flash'] = $flash_msg;
    }

    $this->load->view('graficos/vwGraficos.php', $data);

}

HTML:

            <?php if($show_clientes != FALSE) : ?>

                <?php foreach($show_clientes as $clnt) : ?>
                    <tr>
                        <td>
                            <?= $clnt->data_registro; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>

            <?php endif; ?>

I searched several examples on the net, made queries manually, typing all the syntax, but the result is always the same as the image of the table above. Thanks for your help.

  • Could you inform the structure of the table where you are performing the query and what is the final goal you want to achieve? " Group some dates to display a single record", which would be this single record?

  • It’s a client table, and there’s the field of that customer’s contact record date. As several customers are registered every day, the ultimate goal is to group the amount of contacts during each day. At first this is it. But right now, what I need is for the dates not to be repeated.

1 answer

0


Try grouping before sorting, for example:

MODEL

 $this->db->select();
 $this->db->group_by(); 
 $this->db->order_by(); 
 $this->db->get();
  • Presented the same result. Not grouping.

  • I just found the mistake. In another part of the code, the programmer created a condition to load another function of the client model that was nullifying the function I created to group the records. I used your syntax to better organize my code and make it more readable. Thanks for the help.

Browser other questions tagged

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