在codeigniter中使用php和mysql防止重复输入

Hi i am having trouble in inserting a tracking number in database. it seems that in some cases it generates a duplicate entry. I am generating the tracking number base on the last entry in my first_track table and increment it by 1. now my problem is that when ever the user clicks at the same time. it generates the same tracking number. how do i prevent it? btw here is my code in generating the tracking number. i am also returning the count to 0001 every 1st entry of each month.

<!----------Model-------->
            $this->db->order_by("first_trackid", "desc");
        $query = $this->db->get('first_track');
        if($query->num_rows() > 0)
        {
            $result = $query->result();
            if(date('m') != substr($result[0]->dtsno,2,2)){
                $dtsno = date('ym').'0001';                 
                }
            else{
                $dtsno = $result[0]->dtsno+1;
            }
            return  $dtsno;

        }
        else
        {
            return  $dtsno = date('ym').'0001';                 
        }
<!--- END model------->
<!---controller----------->
//call the model for generating dtsno
$firsttrack->dtsno = $this->user_information_model->dtsno();
//insert to table first_entry
$this->user_information_model->first_track($firsttrack);

First of all, in order to ensure that you do not get duplicated values in the database, make sure you index(Set it as unique) the column ("first_trackid") which is holding the tracking number in the table first_track.

Second, you make use of a temporary track sequence number based on timestamp, when the user initiates the process.

The actual generation of tracking number should take place when the user goes to complete the whole process or in other words, saves the record. At that time, generate that number and display to the user accordingly. In that way, you can ensure that the values will never be duplicated in your schema.

Regards