phpmysqlcodeignitermax

How to get max() of integer value from a varchar field in codeigniter?


rf_id  rf_name  
12      12
13      13
14      14
15      15
16      GF
17      BASE

I want to get 15 from column rf_name in Codeigniter. each time I should get max('rf_name') where characters not allowed


Solution

  • First, make sure column rf_name data type should be integer/float, not varchar/string/text etc.

    So, according to the data type of the column, it will not store any string value

    $maxid = $this->db->query('SELECT MAX(rf_name) AS maxid FROM table')->row()->maxid;
    

    OR

    $this->db->select_max('rf_name');
    $query = $this->db->get('table');
    

    If you have both string and numeric values you have to do the following steps

    1. Get all values of column

      $this->db->select('rf_name');
      $this-db->from('table');
      $values = $this->db->get('table')->result_array(); 
      
    2. Get only values from an array

      $only_values= array();
      foreach($values as $value){
         if (is_numeric($value['rf_name'])) {
            array_push($only_values, $value['rf_name']);
         }
      }
      
    3. use max() and pass the array of values to get maximum numeric value from it.

      $max_value = max($only_values);