使用 PHP 在 Mysql 中存储和检索 JPG

Store and Retrieve JPG in Mysql using PHP

我正在尝试将 jpg 图像存储到 MySQL 数据库中,插入有效但我无法显示结果。

这里是MySQLtable定义:

drop table if exists product_image;
create table product_image(
id_img int not null primary key auto_increment,
name varchar(512),
img LONGBLOB NOT NULL,
id_product int not null
);

PHP 用于存储用户输入文件的脚本:

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="image" >
    <input type="submit" value="Upload" name="submit">
</form>


<?php

$servername = "localhost";
$username   = "root";
$password   = "123456";
$dbname     = "store";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if (isset($_POST['submit'])) {



    $imageName = mysql_real_escape_string($_FILES["image"]["name"]);
    $imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
    $imageType = mysql_real_escape_string($_FILES["image"]["type"]);

    if (substr($imageType, 0, 5) == "image") {

        $sql = "insert into product_image (name,img,id_product) values ('$imageName','$imageData','65') ";

        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }



        echo $imageName, $imageType;
    }

    else {

        echo "select image type:";
    }

}


$conn->close();



?>

</body>
</html>

PHP 显示图像的脚本:

<?php
header("content-type:image/jpg");
$servername = "localhost";
$username   = "root";
$password   = "123456";
$dbname     = "store";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$q      = "select * from product_image";
$result = $conn->query($q);

if ($result->num_rows > 0) {
    // output data of each row
    while ($row = $result->fetch_assoc()) {

        $img = $row["img"];
        #echo "id: " . $row["img"]. "<br>";
        #echo '<img src="data:image;base64, '.$row["img"].' height="200" width="200">';
    }
}

else {
    echo "0 results";
}


echo $img;

$conn->close();

?>

当我调用 PHP 脚本查看图像时,我只看到小图标。有没有我遗漏的东西。

谢谢。

使用这样的东西

<img src="data:image/jpeg;base64,<?php echo base64_encode($row['img']); ?>" class="latest_images img-responsive img-thumbnail" alt="Cinque Terre" >