Select AVG in CodeIgniter

9.1k views Asked by At

Now I have table with all my MySQL results and I want to show average of Cena, Waga and Ilosc from my database at the end row of my generated table.

Model:

public function pokaz_towary($order = 'Nazwa')
    {
        return $this->db->select('ID, Nazwa, Cena, Waga, Ilosc')->
                        order_by($order)->
                        get('towary')->
                        result();
    }

Controller:

$data['query_towary'] = $this->towary_model->pokaz_towary($this->input->get('order'));

View:

if (isset($query_towary))
{
    // Nagłówki
    $this->table->set_heading(array(anchor('?order=id', 'ID'), anchor('?order=nazwa', 'Nazwa'), anchor('?order=cena', 'Cena (PLN)'), anchor('?order=waga', 'Waga (KG)'), anchor('?order=ilosc', 'Ilość'), 'Akcja'));

    foreach($query_towary as $row)
    {
        $akcje = anchor('edytuj?id='.$row->ID ,'Edytuj ');
        $akcje .= anchor('usun?id='.$row->ID , 'Usuń');

        $this->table->add_row(
            $row->ID,
            $row->Nazwa,
            $row->Cena,
            $row->Waga,
            $row->Ilosc,
            $akcje
        );
    }

    echo $this->table->generate();
} ?>
1

There are 1 answers

3
Shaiful Islam On BEST ANSWER

You can use CI $this->db->select_avg() or mysql AVG() in your select statement.

$this->db->select('AVG(Nazwa) avg_Nazwa,AVG(Cena) avg_Cena,AVG(Waga) avg_Waga,AVG(Ilosc) avg_Ilosc');
$result=$this->db->get('towary')->row();

Now you will get average like this

$result->avg_Nazwa;//average of Nazwa
$result->avg_Cena;//average of Cena
$result->avg_Waga;//average of Waga
$result->avg_Ilosc;//average of Ilosc

Hope you can convert this idea to solve your problem.