View Full Version : How to autogenerate a sequential number?

01-07-2004, 10:05 AM
I have a form which I want to start a series of number to identify each of them, starting with an alphabet P and followed by 5 digits, i.e. 10000. Therefore, the first number would be P10000, second P10001, third P10002, and so on. Manually, we can do this by entering this number ourselves in a textbox. But we can forget which previous number we have entered, resulting in duplicating numbers.

I am thinking if PHP can help me to autogenerate this number for me. The first time the textbox should show P10000. Once I save the data and start again with a second form-filling, this time the number should be P10001 and so on.

I guess this is something to do with autoincrement of numbers in MySQL, but I am not sure how this could be linked up with PHP. Any guidance is much appreciated.

Thank you in advance.

01-07-2004, 01:25 PM
I don't think their is a bulletproof way to do this in pure PHP. Not even if you would read/write the number to a textfile (people can get inbetween you reading, computing and writing Unless you apply some stringent lockings but that would impact your performance). Nor if you would do some shared memory stuff to create some sort of application-object (like in ASP) because that's all gone if the server is restarted.

The only way to do this is using a database and have the number created as the value of an auto-number column, when the form is requested.
So you would insert a new record when the form is requested and then grab the value of the aotu-number column (see sticky at top of mySQL forum) and store that in a (hidden?) formfield. Then update that record when the form is submitted (using the autonum-value in the where clause of your updatestatement).

But even then, you would get 'holes' (that is records that do not contain actual formfields) in your sequence if users for some reason don't save the form...

01-07-2004, 02:18 PM
you could store the number as a value in a db field, pull it in php, value++, write value back to the db, write value to the screen (the textbox).

01-07-2004, 02:34 PM
what would be the advantage of that compaired to using an auto-num column?

It will result in much longer tablelockings so it's much less efficient. And it does exactly what an auto-increment does so i don't see the point in doing it like that...

Even if you don't want to use an autoincrement, then you can do it all in one query, by using a subquery to get the max value and increment it.

And if the forms are saved, you'll need a unique identifier and an auto-num column is probably the most secure and efficient way to ensure that.

01-08-2004, 05:09 AM
there may be other data associated with the number. Who knows? Both ways work. And even still, I'd recommend using transactions.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum