Welcome Guest, Not a member yet? Register   Sign In
Problem in passing value from model to controller
#1

[eluser]johnmiller[/eluser]
Hi...

i have a doubt in returning an id from model to controller

The below is a function in my controller

Code:
function add_student()
    {
        $fname = $this->input->post('fname');
        $lname = $this->input->post('fname');
        $this->load->model('student_model');
        $data['query_add_student'] =  $this->student_model->add_student($fname, $lname);

    }

These values pass to the model and insert to the table

Code:
function add_student($fname, $lname)
    {
        $query_add_student = $this->db->query('INSERT INTO student (fname, lname) VALUES ('.$fname.', '.$lname.')');
    
    }


Now i need to return last inserted row id

i tried
Code:
mysql_insert_id())

but i am confused how to write that and return..

how to get the last inserted row id here

i need to return that id to the controller...

and from the controller, i need to view a page using this id

how to write the code in model and controller?

can anyone help me???
#2

[eluser]Phil Sturgeon[/eluser]
All you need to do is:

Code:
function add_student($fname, $lname)
    {
        $this->db->query('INSERT INTO student (fname, lname) VALUES ('.$fname.', '.$lname.')');
        return $this->db->insert_id();

    }
#3

[eluser]JulianM[/eluser]
You should check something like this in your controller (assuming $insert_id is the returned id)

Code:
if ((int)$insert_id > 0)
{
...
}

Julian
#4

[eluser]missionsix[/eluser]
You should also need to escape your $fname / $lname vars.


Code:
function add_student($fname, $lname)
    {
        $this->db->query('INSERT INTO student (fname, lname) VALUES ('. $this->db->escape($fname) .', '.  $this->db->escape($lname) .')');
        return $this->db->insert_id();

    }
#5

[eluser]Rick Jolly[/eluser]
Or...
Code:
function add_student($fname, $lname)
{
    $this->db->set('fname', $fname);
    $this->db->set('lname', $lname);
    $this->db->insert('student');
    return $this->db->insert_id();
}
#6

[eluser]JulianM[/eluser]
Or...

Code:
function add_student($fname, $lname)
{
    $data = array( 'fname' => $fname, 'lname' => $lname );
    $this->db->insert('student', $data);
    return $this->db->insert_id();
}




Theme © iAndrew 2016 - Forum software by © MyBB