-1

I want to generate a unique transaction code with using date an example: PSN-22102021-001 or PSN-22102021001, how to do it?

1 Answers1

0

OK, not sure what database you are using, so will keep this in band. I will assume the PSN is relevant to all codes, as you give no idea what this is. Next, you will find generating unique IDs very difficult, and long, unless they are incremental in some way.

In PHP, you have two options (there are others, but I will let others fill those gaps). microtime(), or uniqid().

If you are using microtime(), you could use the following:

<?php

echo makeID();

function makeID($prefix = 'PRN'){
        $time = str_replace('.', '-', microtime(true) );
        return $prefix.'-'.$time;
}

This would return a number like: PRN-1634871496-0619 However, there is a very small possibility that two times are generated in the same microsecond, and this fails.

To ensure a unique ID, you would need to generate alpha-numeric options such as this..

<?php

echo makeUniqueId();

function makeUniqueId($prefix='PRN'){
        return $prefix.'-'.uniqid();
}

This would return something like PRN-617229f798988

Newish
  • 92
  • 1
  • 7
  • I use mysql as the database, and the ID auto-increment, the PSN code is the starting code for all transaction codes, here the transaction number format is: [PSN-today- increasing serial number], PSN-22102021-001 here, the transaction code I made separately from the ID. – user15798630 Oct 24 '21 at 04:52
  • you're right, PSN relevant to all code – user15798630 Oct 24 '21 at 04:53