Bryan Bryan - 1 year ago 49
SQL Question

Codeigniter SQL query return single value

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.


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?

Answer Source

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; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download