You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP+MySQL生成两类玩家唯一ID?适配皇室战争式需求

解决皇室战争风格的双ID生成问题(PHP + MySQL)

Hey Jake, let's break down how to implement those two unique IDs exactly like Clash Royale does—using PHP and MySQL, we can fix the length and uniqueness issues you ran into with the timestamp+random number approach.

1. 纯数字唯一ID(仅用户本人可见)

Forget the timestamp+random number hack—MySQL's auto-increment primary key is made for this. Here's why it's perfect:

  • Guaranteed unique: MySQL handles incrementing automatically, no duplicates ever.
  • Short length: Use BIGINT UNSIGNED (supports up to 9,223,372,036,854,775,807 users—way more than you'll ever need) and it's just a clean numeric string, no messy long timestamps.
  • Fast queries: Primary keys are indexed by default, so fetching user data via this ID is lightning quick.

Implementation Steps:

  1. Add this to your users table schema:
    CREATE TABLE users (
        user_id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        public_id VARCHAR(16) UNIQUE NOT NULL,
        -- 其他用户字段(用户名、邮箱等)
    );
    
  2. After inserting a new user in PHP, grab the auto-increment ID:
    • With mysqli:
      $conn = new mysqli("localhost", "your_username", "your_password", "your_db");
      $stmt = $conn->prepare("INSERT INTO users (public_id, username) VALUES (?, ?)");
      $stmt->bind_param("ss", $publicId, $username);
      $stmt->execute();
      $privateNumericId = $conn->insert_id;
      
    • With PDO:
      $pdo = new PDO("mysql:host=localhost;dbname=your_db", "your_username", "your_password");
      $stmt = $pdo->prepare("INSERT INTO users (public_id, username) VALUES (?, ?)");
      $stmt->execute([$publicId, $username]);
      $privateNumericId = $pdo->lastInsertId();
      
  3. Show this user_id only when the user is logged into their own account (e.g., in their profile settings).

2. 字母数字组合的唯一ID(所有玩家可见)

For this public ID, we have two solid options—pick whichever fits your needs:

Option A: Base62编码私有数字ID(推荐)

This converts your numeric user_id into a short, alphanumeric string. It's guaranteed unique (each numeric ID maps to exactly one Base62 string), and it's compact (a 10-digit numeric ID becomes a 6-character Base62 string). Plus, you can reverse it later to get back the original user_id if needed.

PHP Base62编码函数:

function base62Encode(int $number): string {
    $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $base = strlen($chars);
    $encoded = '';

    if ($number === 0) {
        return $chars[0];
    }

    while ($number > 0) {
        $encoded = $chars[$number % $base] . $encoded;
        $number = intdiv($number, $base);
    }

    // 可选:补前导零让所有ID长度一致(比如固定6位)
    return str_pad($encoded, 6, '0', STR_PAD_LEFT);
}

使用方式:

生成私有数字ID后,编码得到公开ID:

$publicId = base62Encode($privateNumericId);
// 将这个publicId插入用户表,或者更新用户行

Option B: 随机字母数字串+唯一性校验

如果你想让公开ID完全独立于私有数字ID(避免暴露用户数量),可以生成随机字符串并验证它在数据库中不存在。

PHP随机公开ID生成函数:

function generateRandomPublicId(int $length = 8): string {
    $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charPool = str_split($chars);
    $publicId = '';

    // 生成安全的随机字符串
    for ($i = 0; $i < $length; $i++) {
        $randomIndex = random_int(0, count($charPool) - 1);
        $publicId .= $charPool[$randomIndex];
    }

    // 检查ID是否已存在于数据库
    $conn = new mysqli("localhost", "your_username", "your_password", "your_db");
    $stmt = $conn->prepare("SELECT 1 FROM users WHERE public_id = ?");
    $stmt->bind_param("s", $publicId);
    $stmt->execute();
    $result = $stmt->get_result();

    // 如果存在,递归生成新的ID
    if ($result->num_rows > 0) {
        return generateRandomPublicId($length);
    }

    return $publicId;
}

重要提示:

  • 一定要给MySQL的public_id字段加UNIQUE约束(就像我们在表结构里做的那样),防止并发请求同时生成相同ID的竞态问题。
  • 如果插入时遇到重复错误,只需重试生成新ID即可。

最后建议

  • 私有数字ID绝对不能公开——只在用户登录并查看自己账号时展示。
  • Base62编码方案更高效可靠(无需重试),而随机字符串方案更适合需要完全隐藏用户数量的场景。

内容的提问来源于stack exchange,提问作者Jake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:31:07