Anil
Anil

Reputation: 63

last inserted id in Php codeIgniter

In my model I have return below function for get record id

function getLastInserted()
{
$query = $this->db->select("MAX(`UserID`)+1 as userid")->get("registeration");
return $query->result();            
}

Now I want to pass that ID to mycontroller for record insertion

public function newregistration()
{
if ($this->form_validation->run())
{
$data = array(
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}

Now I want to access model function in controller and pass record id in data function How I do ??

Upvotes: 0

Views: 3551

Answers (3)

Iswarya Swaminadhan
Iswarya Swaminadhan

Reputation: 125

hi i worked out the solution on last inserted id dear here the code:

controller:

function sample() {
   $sid=$this->adminmodel->getLastInserted();
   $this->adminmodel->newregistration( $sid);
  }

model:

function getLastInserted()
  {
 $query = $query = $this->db->select('id')->order_by('id','desc')->limit(1)->get('employee_outs')->row('id');
return $query;            
}

model:

   public function newregistration($sid)
   {
     if ($this->form_validation->run())
    {
    $data = array(
    'UserID'=> $sid,
    'Name' => $this->input->post('Name'),
    'MobileNo' => $this->input->post('MobileNo'),
    'IMEINumber' => $this->input->post('IMEINumber'),
    'City' => $this->input->post('City')
    );
    $this->adminmodel->insertregistration($data);
}
  }

Upvotes: 0

Hikmat Sijapati
Hikmat Sijapati

Reputation: 6994

In Controller load your model first using

$this->load->model('model_name');

Then call to model's getLastInserted() function.

$ID = $this->model_name->getLastInserted();//you will get id here

In model return $query->row()->userid; insead return of $query->result().

Then modify the controller:

public function newregistration()
{
    if ($this->form_validation->run())
    {
        $data = array(
        'UserID'=> $this->model_name->getLastInserted(),
        'Name' => $this->input->post('Name'),
        'MobileNo' => $this->input->post('MobileNo'),
        'IMEINumber' => $this->input->post('IMEINumber'),
        'City' => $this->input->post('City')
        );
        $this->adminmodel->insertregistration($data);
    }
}

Upvotes: 0

cyriac
cyriac

Reputation: 101

set return in model and in controller write

$insert_id=$this->db->insert_id();

Upvotes: 1

Related Questions