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

PHP+MySQL实现数据库图片在表格中显示的问题求助

问题解决:数据库存储的图片无法在表格中显示

问题原因

你直接将数据库中存储的图片二进制内容输出到表格单元格,浏览器无法解析原始二进制数据为可显示的图片,因此显示为乱码或无意义字符。

解决方案

方案1:使用Data URI直接嵌入图片

修改表格显示代码中输出图片的行,将二进制内容转为Base64编码,通过Data URI格式嵌入<img>标签:

原代码:

echo "<td>" . $row['image'] . "</td>";

替换为(假设图片为JPEG格式):

echo "<td><img src='data:image/jpeg;base64," . base64_encode($row['image']) . "' alt='Obra Image' style='max-width: 200px; max-height: 200px;'></td>";

优化:动态匹配图片类型

如果上传的图片格式不固定(PNG/GIF等),建议修改上传逻辑,同时存储图片的MIME类型:

  1. 在servico表中新增image_type字段,类型为VARCHAR(50)。
  2. 修改上传代码:
$msg = '';
if($_SERVER['REQUEST_METHOD']=='POST'){
    $image = $_FILES['image']['tmp_name'];
    $img = file_get_contents($image);
    // 获取图片MIME类型
    $image_type = $_FILES['image']['type'];
    
    $con = mysqli_connect('localhost','root','','oil') or die('Unable To connect');
    // 更新SQL语句,加入image_type字段
    $sql = "insert into servico (image, image_type) values(?, ?)";

    $stmt = mysqli_prepare($con,$sql);
    // 绑定两个参数
    mysqli_stmt_bind_param($stmt, "ss",$img, $image_type);
    mysqli_stmt_execute($stmt);

    $check = mysqli_stmt_affected_rows($stmt);
    if($check==1){
        $msg = 'Image Successfullly UPloaded';
    }else{
        $msg = 'Error uploading image';
    }
    mysqli_close($con);
}
  1. 此时显示代码可动态适配图片类型:
echo "<td><img src='data:" . $row['image_type'] . ";base64," . base64_encode($row['image']) . "' alt='Obra Image' style='max-width: 200px; max-height: 200px;'></td>";

方案2:通过独立脚本输出图片

适合较大图片,避免页面体积过大:

  1. 创建get_image.php文件:
<?php
$con = mysqli_connect("localhost", "root", "", "oil");
if (mysqli_connect_errno()) {
    die("Falha ao conectar a MySQL: " . mysqli_connect_error());
}

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($id > 0) {
    $stmt = mysqli_prepare($con, "SELECT image, image_type FROM servico WHERE idObra = ?");
    mysqli_stmt_bind_param($stmt, "i", $id);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $image, $image_type);
    mysqli_stmt_fetch($stmt);
    
    if ($image && $image_type) {
        header("Content-Type: " . $image_type);
        echo $image;
    } else {
        header("HTTP/1.0 404 Not Found");
        echo "Image not found";
    }
} else {
    header("HTTP/1.0 400 Bad Request");
    echo "Invalid ID";
}

mysqli_close($con);
?>
  1. 修改表格显示代码中的图片输出行:
echo "<td><img src='get_image.php?id=" . $row['idObra'] . "' alt='Obra Image' style='max-width: 200px; max-height: 200px;'></td>";

额外建议

虽然可以将图片存储在数据库中,但更推荐将图片保存到服务器文件系统,仅在数据库中存储图片文件的路径,这种方式性能更优,也更便于图片管理。

内容的提问来源于stack exchange,提问作者bruno.slash.lima

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:20:26