Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use getLastInsertId() in CakePHP in 2.4.1 version?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.10k
    Comment on it

    Hi Reader's,
     Welcome to FindNerd, today we are going to discuss how to use getLastInsertId() in CakePHP in 2.4.1 version?

    In CakePHP there are two methods for getting the last inserted id

    1-Model::getLastInsertID()
    2-Model::getInsertID()

    Suppose you want to get last insert id after saving some data in database, you have to use getLastInsertId() method or getInsertID() to find last inserted from database.

    Let see how it is used in CakePHP

    <?php
    
    $user_id= $this->ModelName->getInsertID();
    $user_id= $this->ModelName->getLastInsertID();
    
     ?>

    In place of ModelName you have to passed your model name.

    let take model name is User in which insert following data.

    <?php 
                 //define here parameter to insert in model
                  $data['username'] = $this->data['username'];
                  $data['first_name'] = $this->data['first_name'];
                  $data['last_name'] = $this->data['last_name'];
                  $data['last_name'] = $this->data['email'];
                  $data['password'] = $this->data['password'];
                  $data['role_id'] = $this->data['role_id'];
                  $data['status']=1;
                    
                  $result['users']= $this->User->save($data);//here data will insert in to User model
         
           ?>

     So if you want to get last insert id which is last record has been inserted, So for this   you have to use below code.

     <?php
           $user_id= $this->User->getLastInsertId();
    
      ?>

     Here user is a model name, when you print $user_id then it will return the last insert  id which is last inserted data in User modal.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: