Skip to content
Advertisement

Creating an auto incremented id when user submits a form

Currently I have a refno. column in my database with the format LP00001. Now I have a add page that inserts all data that the user inserts in the input field and all this data gets sent to a table in my database, but my refno column stays null which I want to have an auto incrementing value where the last 5 digits will be +1 everytime the user submits the form.

I do not want to have it be shown before the submit button as 2 users can be on that page at the same time which means they both will get the same id which means it has to generate it only at the time of submit. Currently this is my code:

Controller class:

if ($this->form_validation->run() == FALSE)
        {
            $main['page'] = 'crm/listings/add';
            $this->load->view('crm/index', $main);
        }else {  
            $maindata=array('clients_id'=>$this->session->userdata('clientsessid'),
            'property_for'=>$this->security->xss_clean($this->input->post('property_for')),
            'property_type'=>$this->security->xss_clean($this->input->post('property_type')));
            $insertid=$this->listings_model->insert_listing($maindata);
            if($insertid){
                $this->session->set_flashdata('message', '<div>Successfully</div>');
                redirect('listings/sales');

Model Class:

function insert_listing($maindata){
    $this->db->insert("crm_listings",$maindata);
    $prime=$this->db->insert_id();
    return $prime;
}

So I assume I’ll need to do this in my model class function insert_listing since that is called when I press submit button. Here another thing will be that the model will have to check what was the last entry in the database that has to be incremented for which I’m assuming I’ll have to use echo str_replace("LP","","LP00001");

Advertisement

Answer

I guess you just have to prepend the initials LP to the returned autoIncremented id.

function insert_listing($maindata){
    // ...

    $this->db->set("refno", "LP". sprintf('%05d', $prime));
    $this->db->where('id', $prime);
    $this->db->update("crm_listings");

    return $prime;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement