0

I need last test(table) id. If I use (in SQL) 'SELECT MAX(id) FROM test, then show the last id. But when I use that in my model, showing error.

Codes from model (Test_model):

function get_test_table_last_id() {
    $test_table = $this->db->dbprefix('test');

    $sql = "SELECT MAX($test_table.id) AS last_id FROM $test_table";

    return $this->db->query($sql)->row()->last_id;
}

Codes from controller (Test controller):

$model_info = $this->Test_model->get_test_table_last_id()->last_id;
$view_data["last_id"] = $model_info;

$this->load->view("test_view/view", $view_data);

Codes from view (test_view):

<?php echo $last_id ?>

I'm getting this error:

Derk Jan Speelman
  • 11,291
  • 4
  • 29
  • 45

4 Answers4

1

In your function get_test_table_last_id(), you return the last_id value of the query...

return $this->db->query($sql)->row()->last_id;
//                                   ^^^^^^^^

and then you try and use...

$model_info = $this->Test_model->get_test_table_last_id()->last_id;
//                                                        ^^^^^^^^

So this is trying to get the last_id again. Just use the return value as it is...

$model_info = $this->Test_model->get_test_table_last_id();
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
0

You need to return an array like this one:

function get_test_table_last_id() {

$test_table = $this->db->dbprefix('test');

$sql = "SELECT MAX($test_table.id) AS last_id FROM $test_table";

return $this->db->query($sql)->row_array();

}

rrsantos
  • 404
  • 4
  • 14
0

SELECT MAX(ID) AS last_id FROM table

mitesh
  • 147
  • 1
  • 9
0

Remove ->last_id from as described.

Codes from controller (Test controller):

// $model_info = $this->Test_model->get_test_table_last_id()->last_id;
$model_info = $this->Test_model->get_test_table_last_id();
$view_data["last_id"] = $model_info;

$this->load->view("test_view/view", $view_data);
Himanshu
  • 251
  • 4
  • 18