dragon0023 2017-06-05 03:57
浏览 54

主键 - 随机字节好或坏

Ive read a few articles on this subject and just wanted to get some clarificiation regarding using random primary keys instead of auto increment. I am building an application and instead of using auto-increment primary keys, I am using the following code to generate a random primary key that includes both numbers and letters:

$bytes = random_bytes(8);
$bytes = bin2hex($bytes);

The reason I would like to use random primary keys is to prevent url tampering. My application also has record level security but I wanted random primary key as a secondary measure. Also, I have this column set to unique as to prevent any rare collisions. If there is a collision i just throw on on screen error asking using to resubmit the form which generates another random key. So my questions are as follows:

  1. My db is innodb and my application is all relationship based (PK/FK relationships). Does having a random key (using the code above) effect search performance and/or indexing speed as compared to auto increment key?
  2. Are there any reasons I should not be using a random key (as the primary / indexed key) other than possible collision which I have protected against using duplicate error handling?
  3. Before I finalize this application, are there any other suggestions or best practices I should be using as it relates to primary key other than how I am doing it above?

Thank you. Again, i know there are other articles out there but many of them are outdated (prior to php 7 random bytes) so I thought id get a fresh take on whether or not random primary keys are considered best practice (why or why not). Thanks.

  • 写回答

1条回答 默认 最新

  • dongyi2534 2017-06-05 07:41
    关注

    Bad -- very bad, in fact. Random primary keys play havoc with MySQL's page cache, which will make performance poor under load. It also means some SQL features will be unavailable to you, like multiple-row INSERT.

    If you want to protect the ID in a URL from tampering, consider including a keyed hash (e.g, HMAC) of the identifier in the URL.

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集