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

PHP预编译语句向MySQL Binary(16)插入UUID报错求助

解决MySQL 5.6中UUID插入Binary(16)时的Collation冲突问题

从你给出的错误信息来看,问题核心是MySQL排序规则(collation)不匹配:Illegal mix of collations错误说明REPLACE(UUID(), '-','')操作里的几个字符串(UUID()返回值、'-'、空字符串)使用了不同的collation,MySQL 5.6对这类混合操作的校验比较严格。

下面给你两种可行的解决方案:

方案一:在SQL语句中显式统一Collation

你可以通过转换UUID()的字符集,或者指定替换字符的collation来消除冲突,只需修改INSERT语句中的user_id部分:

方式1:转换UUID()的字符集

把UUID()的结果转换为和你的数据库/表一致的字符集(比如utf8_unicode_ci):

INSERT INTO " . $this->table_name . " SET user_id = UNHEX(REPLACE(CONVERT(UUID() USING utf8), '-', '')), name = :name, email = :email, password = :password

方式2:指定替换字符的Collation

给'-'显式指定和UUID()结果匹配的collation:

INSERT INTO " . $this->table_name . " SET user_id = UNHEX(REPLACE(UUID(), _utf8'-' COLLATE utf8_unicode_ci, '')), name = :name, email = :email, password = :password

方案二:在PHP端生成并处理UUID(更推荐)

把UUID的生成和二进制转换逻辑移到PHP端,完全避开MySQL端的collation问题,同时代码逻辑更清晰:

修改你的create函数如下:

function create() { 
    // 生成符合RFC4122标准的UUID
    $uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000,
        mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
    
    // 去掉'-'并转为二进制
    $uuidBinary = hex2bin(str_replace('-', '', $uuid));

    $query = "INSERT INTO " . $this->table_name . " SET user_id = :user_id, name = :name, email = :email, password = :password"; 
    $stmt = $this->con->prepare($query); 

    $this->name = htmlspecialchars(strip_tags($this->name)); 
    $this->email = htmlspecialchars(strip_tags($this->email)); 
    $this->password = htmlspecialchars(strip_tags($this->password)); 

    // 绑定二进制参数时指定类型
    $stmt->bindParam(':user_id', $uuidBinary, PDO::PARAM_LOB);
    $stmt->bindParam(':name', $this->name); 
    $stmt->bindParam(':email', $this->email); 
    $password_hash = password_hash($this->password, PASSWORD_BCRYPT); 
    $stmt->bindParam(":password", $password_hash); 

    if ($stmt->execute()) { 
        return true; 
    } 
    print_r($stmt->errorInfo()); 
    return false; 
}

如果你需要更规范的UUID生成,推荐使用ramsey/uuid库(通过Composer安装),生成代码会更简洁可靠。

额外建议

检查你的数据库、表的collation设置,确保它们保持一致(比如统一为utf8_unicode_ci),避免后续再出现类似的collation冲突问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 18:47:47