Create a unique identifier

I use the function to create a unique identifier using the last identifier from the table. But the problem arises when a person opens at about the same time. Could you suggest any fix in the current function? Since this function is used in production and on a live server, a small code adjustment will be much better.

Here is a 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 be genrate: APN / 0371

+4
source share
2 answers

Use the MySQL AUTO_INCREMENT function in the ID column. It will do each row with an incremental unique identifier.

More details.

+6
source

It is not safe to query the database for the last identifier, increment, and then rely on the fact that this identifier will be unique as you run it, the identifier can and will be used by several users at the same time if they open the page at the same time.

The way to do this is to insert into the database table, which uses the auto_increment field, and after success, get the last insert identifier as the main key. This is done using the mysql PHP function mysql_insert_id () . CodeIgniter also has this functionality using insert_id () , which is a simple wrapper for PHP mysql_insert_id () .

 $this->db->insert_id(); 
+5
source

Source: https://habr.com/ru/post/1397956/


All Articles