如何使用MYSQLI实现向MySQL插入blob类型的图片数据
你现有的mysqli代码无法正常插入blob类型数据,核心问题是mysqli的b(blob)类型参数不能直接通过mysqli_stmt_bind_param传值,需要用mysqli_stmt_send_long_data方法分块发送二进制数据。
以下是修正后可正常运行的mysli版本实现:
function changeAvatar($conn, $userId, $file, $filename, $filesize, $filetype){ // 字段名name、type是MySQL保留关键字,用反引号包裹避免语法冲突 $sql = "INSERT INTO avatars (usersId, `name`, image, size, `type`) VALUES (?, ?, ?, ?, ?);"; $stmt = mysqli_stmt_init($conn); if(!mysqli_stmt_prepare($stmt, $sql)){ header("location: ../profile.php?error=stmtfailed"); exit(); } // 类型对应:i=用户id(int), s=文件名(string), b=图片内容(blob), i=文件大小(int), s=文件类型(string) // blob类型参数位置先填null占位 mysqli_stmt_bind_param($stmt, "isbis", $userId, $filename, $null, $filesize, $filetype); // 分块发送二进制blob数据,每块8192字节,避免大文件传输失败 $chunkSize = 8192; $offset = 0; while ($chunk = substr($file, $offset, $chunkSize)) { // 第二个参数为blob参数的索引,从0开始计数,这里image是第三个参数所以索引为2 mysqli_stmt_send_long_data($stmt, 2, $chunk); $offset += $chunkSize; } mysqli_stmt_execute($stmt); // 注意:不建议将整个图片二进制存入SESSION,会严重占用服务器存储资源,建议存头像记录ID,需要展示时单独查询输出 // $_SESSION["avatar"] = $file; mysqli_stmt_close($stmt); header("location: ../profile.php?error=none"); exit(); }
额外注意事项
- 数据库
avatars表的image字段类型请设置为MEDIUMBLOB(最大支持16MB)或LONGBLOB(最大支持4GB),默认BLOB类型仅支持最大64KB的数据,超过大小会插入失败。 - 检查
php.ini配置中的upload_max_filesize和post_max_size参数,确保其值大于你允许上传的头像最大体积。
内容的提问来源于stack exchange,提问作者MousTea
相关产品推荐
相关产品推荐

