dua27031 2019-04-12 12:33
浏览 167

散列随机值加上自动增量数是否确保唯一性?

I'm trying to generate a unique order number for my ecommerce application, this is my code:

<?php
 $bytes = random_bytes(3);
 $random_hash = bin2hex($bytes);
 $order_num = $random_hash . "1";
 echo strtoupper(hash('crc32b', $order_num));

The order number (in the example is 1), is going to be an auto-increment value retrieved from MySQL. Does this ensure me uniqueness?

I wanted a short max 8-10 chars unique final value. An only numbers solution would be fine too.

  • 写回答

2条回答 默认 最新

  • dtdd25012 2019-04-12 13:16
    关注

    As far as I know, most hash algorithms make no guarantee of when collisions might occur, so you're probably just as likely to get a collision with your proposed code as using the random part on its own.

    If the auto-increment part is unique, and the random part is just to avoid guesses, you could just concatenate the two parts together (i.e. everything in your example before the hash call). That way if the same random number comes up twice, it will have different numbers on the end.

    If that results in something too long, you could do something with base_convert or asc to convert the number into a shorter representation.

    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置