【问题标题】:Why are my images echoed in these weird characters?为什么我的图像在这些奇怪的字符中回响?
【发布时间】:2018-06-24 20:41:51
【问题描述】:

我使用这个将图像插入到我的 phpmyadmin 数据库中:

UPDATE
inventory
SET
IMG = LOAD_FILE('A:/Programs/XAMPP/htdocs/SamsCarLot/images/mercedes-benz.jpg')
WHERE
VIN = 'WDDGF8AB9DR298549';

当我尝试将它回显到我的网页上时,我得到了这些看起来很奇怪的字符 click to view photo

我确定我的语法是正确的,如果不正确,请纠正我,但我不知道为什么我的图像会从我的数据库中将自己转换为这些时髦的字符。

<?php
$vin = mysqli_real_escape_string($conn, $_GET['VIN']);
$sql = "SELECT * FROM inventory WHERE VIN = '$vin'";
$result = $conn->query($sql);
$stmt = $conn->prepare("SELECT Model FROM inventory WHERE VIN = ?");
$stmt->bind_param("s", $vin);
$stmt->execute();
$stmt->bind_result($model);
$stmt->fetch();
echo "<h1>$model</h1>";


// Loop through all the rows returned by the query, creating a table row for each
while ($result_ar = mysqli_fetch_assoc($result)) {
  $img = $result_ar['IMG'];
  $year = $result_ar['YEAR'];
  $make = $result_ar['Make'];
  $model = $result_ar['Model'];
  $trim = $result_ar['TRIM'];
  $color = $result_ar['EXT_COLOR'];
  $interior = $result_ar['INT_COLOR'];
  $mileage = $result_ar['MILEAGE'];
  $transmission = $result_ar['TRANSMISSION'];
  $price = $result_ar['ASKING_PRICE'];
}
echo "<IMG src='$img' width='250'>";
echo "$year $make $model</p>";
echo "<p>Asking Price: $price </p>";
echo "<p>Exeterior Color: $color</p>";
echo "<p>Interior Color: $interior </p>";

$conn->close();
//INSERT INTO images (img) VALUES ('A:/Programs/XAMPP/htdocs/Sam'sCarLot/images/ferrari.jpg')
?>

【问题讨论】:

  • 您是否将图像作为 blob 存储在数据库中?
  • LOAD_FILE 读取文件并将内容作为字符串返回 - 所以您所看到的基本上是正确的。然而,最好只存储图像的路径而不是像这样的 blob
  • 是的,作为 LONGBLOB
  • 更新库存 SET IMG = LOAD_FILE('A:/Programs/XAMPP/htdocs/SamsCarLot/images/mercedes-benz.jpg') WHERE VIN = 'WDDGF8AB9DR298549';是我知道如何将图像存储在数据库中的唯一方法。我是新手,我以前从未使用过 sql 脚本来存储图像,当我用谷歌搜索如何做到这一点时,我得到了代码

标签: php html sql image phpmyadmin


【解决方案1】:

如果存储为 blob,则显示图像

echo "<img src='data:image/jpeg;base64, " . base64_decode( $img ) . "' />";

【讨论】:

    【解决方案2】:

    您将图像作为二进制数据存储在数据库中(blob 列)。当您显示图像时,您会将二进制数据放入您的img-tag 的src 属性中。

    您需要提供图像的链接(例如,一个单独的 PHP 文件,从数据库中查询图像并将其输出到浏览器)或使用正确的数据编码。

    带有额外 php 文件的示例:

    $vin = $_GET['vin']; 
    $stmt = $conn->prepare("SELECT Model FROM inventory WHERE VIN = :vin");
    $stmt->bind_param(":vin", $vin);
    $stmt->execute();
    $row = $stmt->fetch();
    
    // Output image
    header('Content-Type: image/jpeg'); // For jpg-files
    echo $row[0];
    

    编码示例:https://stackoverflow.com/a/27696825/1392490

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 2014-08-12
      • 2020-09-05
      • 1970-01-01
      相关资源
      最近更新 更多