phpcodeignitermaxquery-builderresultset

How to get Select max value in codeigniter


Controller:

$next_id = $this->o->next_id();
$data['next_id']=$next_id;

Model:

public function next_id(){
    $this->db->select_max('p_ori_id');
    $max = $this->db->get('orientation_master');
    if($max==0){
        $next_id = 1;
    }else{
        $next_id = 1+$max;
    }
    return $next_id;
}

Return Error:

Object of class CI_DB_mysqli_result could not be converted to int

Please solve problem..


Solution

  • No offense to @pradeep but you may have some unexpected results if you don't have any rows. I suggest:

    public function next_id()
    {
       $this->db->select_max('p_ori_id', 'max');
       $query = $this->db->get('orientation_master');
       if ($query->num_rows() == 0) {
          return 1;
       }
       $max = $query->row()->max;
       return $max == 0 ? 1 : $max + 1;
    }