It would be easier to use formmail's nextnum feature. Keep in mind that nothing you do is going to be 100% accurate due to user errors in filling out the form. Otherwise, what you are asking for is a php programming exercise.
This function returns a number which increments on each form submission. You can use this value as a unique number or a sequence number. Note that it's possible for there to be gaps in the values (you can't rely on the numbers being sequential) due to user or other errors.
To enable this function, you must create a file on your server in which FormMail will store the next number to be returned. For instructions on how to do this, see the NEXT_NUM_FILE configuration setting.
You can also specify an optional padding amount and an optional base or radix for the number returned. The format is:
Both pad and base are optional, but if you want to use base, you must also specify pad. The padding value ensures you get no less than that many digits padded on the left with zeroes.
<input type="hidden" name="derive_fields" value="