Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group By with CodeIgniter [closed]

I use CodeIgniter for my project and this is my code in model

public function group_all_ville(){  
        $this->db->select('*');
        $this->db->from('departement');
        $this->db->join('villes', 'villes.num_dept = departement.num_dept');
        $this->db->group_by('nom_dept'); 
        $query = $this->db->get(); 
        return $query->result();
    }

and this is error after execution

A Database Error Occurred

Error Number: 1055

Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'pneu.departement.id_dept' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

SELECT * FROM `departement` JOIN `villes` ON `villes`.`num_dept` = `departement`.`num_dept` GROUP BY `nom_dept`

Filename: C:/wamp64/www/pneu/system/database/DB_driver.php

Line Number: 691

I try different method but nothing result. Thanks

like image 287
Tojo Avatar asked Jan 04 '17 20:01

Tojo


People also ask

How to close db connection in CodeIgniter?

There is a db->close() method. In a PHP environment that is not using persistent connections there is no real need to call it. For MySQL in particular, all open non-persistent MySQL connections and result sets are automatically destroyed when a PHP script finishes its execution.

How do I print last query?

We can get last executed query using last_query() function of db class in codeigniter. It is a very simple to use $this->db->last_query() function to see SQL statements of last executed query in php codeigniter app.

What is query Builder in CodeIgniter?

CodeIgniter gives you access to a Query Builder class. This pattern allows information to be retrieved, inserted, and updated in your database with minimal scripting. In some cases only one or two lines of code are necessary to perform a database action.


2 Answers

use order_by clause as well

$this->db->group_by('nom_dept'); 
$this->db->order_by('nom_dept', 'asc');  # or desc

FYI : Setting SQL mode and Session set is not fix the actual error.

Examples (Better not to Do)

  1. https://stackoverflow.com/a/35729681/4595675
like image 112
Abdulla Nilam Avatar answered Sep 24 '22 10:09

Abdulla Nilam


This solution worked for me:

$this->db->select('d.nom_dept');
$this->db->from('departement AS d, villes as v');
$this->db->where('v.num_dept = d.num_dept');
$this->db->group_by('d.nom_dept');

Refer to 12.20.3 MySQL Handling of GROUP BY for more information.

like image 20
Tojo Avatar answered Sep 22 '22 10:09

Tojo