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
Use MySQL's AUTO_INCREMENT
feature on the ID column. It will make each now row with an incremental unique ID.
Read more.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With