8

I am using PHP/MySQL, to generate a counter code for the each entry while opening the entry screen.

Here is the code I am using

$qresult = $db->query("SELECT count(*) FROM ap_aurora_projects");
$row = $qresult->fetch_row(); 
$slno = $row[0] + 1;

$today = date("ymd");

$code = $today . "-" . $slno;

This code is generating correctly and showing to user before he creates the record. The issue is when multiple users open same time the code is duplicating in their screens.

What is the method to avoid the duplicates.

I tried to create a separate table to store the latest number and incremented for each request, but the issue is, if user cancel the entry, that number is missing.

EDIT

The code is working properly when one user generate the code and insert the record. But the issue is if multiple users opens simultaneously it generates same number to them in their screen. If all of them try to save the record it is getting duplicated. Please note that, I generate this number and show in the entry screen initially not while saving the record.

5
  • How exactly is the code duplicating? I can see only SELECT query which is safe and all users should see the same output unless DB changed in some other part of code. You should provide more of your code. Commented Aug 30, 2011 at 0:48
  • how the ap_aurora_projects records are inserted? every request? Commented Aug 30, 2011 at 1:02
  • What requirements does the code have? However, you cannot use the COUNT() of rows if you need to show the code before the INSERT().
    – Dr.Molle
    Commented Aug 30, 2011 at 1:02
  • what is the ap_aurora_projects table structure? Commented Aug 30, 2011 at 1:05
  • the code should generate 110829_1, 110829_2 like this (ymd).
    – AjayR
    Commented Aug 30, 2011 at 1:05

3 Answers 3

7

I suppose the code you show in the question is simplified and you can't use AUTO_INCREMENT column as suggested by another answer.

You will need to lock the table for reading until it's updated. Do the MySQL queries in the following order:

LOCK TABLES ap_aurora_projects READ;
SELECT count(*) FROM ap_aurora_projects WHERE ...;
//Update here ...
UNLOCK TABLES;

More about locking whole tables can be found here: http://dev.mysql.com/doc/refman/5.6/en/lock-tables.html

If you are using InnoDB storage engine, you can read more about advanced (row) locking and transactions here: http://dev.mysql.com/doc/refman/5.6/en/innodb-transaction-model.html

2
  • It may not help in my case, as I need to allow multiple users to generate the number at a time.
    – AjayR
    Commented Aug 30, 2011 at 1:28
  • 1
    It will work because the LOCK TABLE statement will wait until the other script finish and release the lock. (if the table is already locked) Commented Aug 30, 2011 at 1:36
6

Here's what you need to do:

First, create a table:

create table uniqueId ( id bigint(20) unsigned not null auto_increment primary key );

Second, use this code (I don't know which MySQL code you use, so I will use the common one):

$link = mysql_connect('localhost', 'user', 'password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT IGNORE INTO uniqueId VALUES (NULL);");
printf("Last inserted record has id %f\n", date("ymd") . "-" . mysql_insert_id());

By inserting and not selecting, you are sure you will not have duplicate.

4

Creating your own autoincrementing identifier is difficult and error-prone as you've discovered. You should think about using the MySQL AUTO_INCREMENT feature and the corresponding LAST_INSERT_ID() function which will return the id of the most recently inserted record in that session.

Key excerpt from that link:

These functions are connection-specific, so their return values are not affected by another connection which is also performing inserts.

You will have to change your approach however. Instead of showing an ID in the screen before the record is created, you'll need to wait until the insert of the record. OR if you REALLY need to show this ID then insert a blank record to create and return the ID and then edit that record from user-entered data rather than performing an insert.

One worrisome idea is that you're needing to show the internal primary key to the user of the system. The key is not natural (such government-issued identifiers) and it is generated by the system. This smells a bit of bad design. Typically primary key values are never shown to the user and some other surrogate identifier is used.

2
  • I totally agree with you. However, this is number is some kind of reference number (not row identifier) for the users who will note it down for the further communication.
    – AjayR
    Commented Aug 30, 2011 at 1:28
  • Right. That makes sense but I don't see why the reference number has to exist before the actual business object exists in the database... or why it seems to to have to be a monotonically increasing set of integers. There are several other ways of creating unique IDs.
    – Paul Sasik
    Commented Aug 30, 2011 at 11:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.