1

I am working with CodeIgniter and I want to get the highest ID out of a table. This i realize with a function in the Model. But I don't get the result, which is a single value, as value back.

Code:

 function get_highest_answer_id(){
   $this->db->query('SELECT MAX(id) AS answerid FROM pa_it_answer;');
    if ($query = $this->db->get()) {
        if ($query->num_rows() > 0) {
            return $query->result();
        } else {
            return array();
        }
    } else {
        return FALSE;
    }
}

How do I have to Change the code that when I call this function in my Controller I get the single value?

1
  • max returns single value if you dont group the query. Commented Jul 27, 2017 at 11:46

4 Answers 4

3

Below code is works fine for me.

$MAXID = 0;
$row = $this->db->query('SELECT MAX(id) AS answerid FROM pa_it_answer')->row();
if ($row) {
    $MAXID = $row->answerid; 
}
Sign up to request clarification or add additional context in comments.

Comments

0

Change your query in codeigniter like this

function get_highest_answer_id(){
     $this->db->select('MAX(id) AS answerid');
        if ($query = $this->db->get('pa_it_answer')) {
            if ($query->num_rows() > 0) {
                return $query->result();
            } else {
                return array();
            }
        } else {
            return FALSE;
        }
    }

Comments

0

You just have to simplify your method with row()

function get_highest_answer_id(){
        $record = $this->db->query('SELECT MAX(id) AS answerid FROM pa_it_answer;')->row();
        if ($record) {
            return $record->answerid;
        } 
        else {
            return FALSE;
        }
    }

Comments

0

Try this:

function get_highest_answer_id(){
   $this->db->query('SELECT MAX(id) AS answerid FROM pa_it_answer;');
    if ($query = $this->db->get()) {
        if ($query->num_rows() > 0) {
            return $query->row(); // here!!!
        } else {
            return array();
        }
    } else {
        return FALSE;
    }
}

I recommended use the querybuilder of CI (EDITED)

$this->db->select_max('id', 'answerid');
$query = $this->db->get('pa_it_answer');

var_dump( $query );
var_dump( $query->answerid );
die();

2 Comments

When I try MikeSoutos solution there Comes the message: A Database Error Occurred Error Number: 1096 No tables used SELECT * Filename: C:/..../application/models/Model.php Line Number: 825
Hi! The recommended soluction? I edit the post to adapted the recommended solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.