Unique, unpredictable, 12 digit, integer id

前端 未结 7 1179
被撕碎了的回忆
被撕碎了的回忆 2021-01-13 06:56

How would I go about generating this... I want to keep my primary key sequential and have a 12 digit unique pin generated for each new object added to the database.

7条回答
  •  我在风中等你
    2021-01-13 07:18

    Generally, I will prefer to do something a little bit more low tech. I obscure the values in PHP and leave them as auto-incrementing in JS.

    $seeds = array( /*series 100 of very large >= 10-digit numbers*/ );
    $seedID = rand( count( $seeds ) ); // randomly choose one of those.
    // a string combination which represents the ID + some hash.
    $id = bcadd( $seeds[ $seedID ], /* id retrieved from database */ );
    // make sure we've not accidentally passed the 10^12 point
    $id = bcmod( $id, 1000000000000 );
    // make sure to pad
    $id = str_pad('' .  $id, 3, "0", STR_PAD_LEFT);
    $outID = substr( $id, 0, 5 ) . $seedID . substr( $id, 6 );
    

    Then, when receiving the ID from the user:

    $seedID = substr( $outID, 6, 2 );
    $tmpID = substr( $outID, 0, 5 ) . substr( $outID, 8 );
    $id = bcsub( $tmpID, $seeds[ $seedID ] );
    // we passed the modulus se we need to add this back in.
    if( $id < 0 ) $id = bcmod( bcadd( $id, 1000000000000 ), 1000000000000 );
    

    This will basically mean that you're simply obscuring whatever number you want -- you can use auto_increment with impunity!

提交回复
热议问题