Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creation of unique id

I'm using function for creating unique id using last id from table. But problem comes when person opens at approxmately at same time. Could you please suggest any rectification in current function? Since this function is used in production and on live server, a little tweak in code will be far better.

Here is function using:

function approvalNumber()
    {
        $data=array();
        $text = "APN/";
        $position = "front";
        $this->db->order_by('approval_id','desc');
        $this->db->limit('1','0');
        $query=$this->db->get('approval_note');
        if($query->num_rows()>0)
        {
            foreach($query->result_array() as $row){
                $data[] = $row;                 
            }
        }
        $query->free_result();
        if(count($data))
        $id=str_pad((int) $data['0']['approval_id']+1,4,"0",STR_PAD_LEFT);
        else
        $id='0001';
        return $approvalNo = $text.$id; 
    }

This will genrate : APN/0371

like image 263
user762641 Avatar asked Dec 21 '22 01:12

user762641


2 Answers

Use MySQL's AUTO_INCREMENT feature on the ID column. It will make each now row with an incremental unique ID.

Read more.

like image 153
Madara's Ghost Avatar answered Dec 24 '22 03:12

Madara's Ghost


It is not safe to query the database for a last ID, increment, and then rely on that ID to be unique as you've run into, the ID can and will be used at the same time by multiple users if they open the page at the same time.

The way around this is to insert into the database table which employs an auto_increment field, and upon success obtain the last insert id as your primary key. This is done using the PHP mysql function mysql_insert_id(). CodeIgniter has this functionality as well using insert_id(), which is a simple wrapper for the PHP mysql_insert_id() function.

$this->db->insert_id();
like image 27
Highway of Life Avatar answered Dec 24 '22 03:12

Highway of Life