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

标签 php mysql blob php-5.3

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

这是 MySQL 表定义:

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" >

关于php - 使用 PHP 在 Mysql 中存储和检索 JPG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30436864/

相关文章:

php - 使用 wp_remote_get() 函数获取图像时出错

c# - MySql 存储过程参数转义

PHP 不将数据保存到数据库

javascript - 使用 Apps 脚本在内存中创建一个新的 blob

php - $row 没有正确地回显来自 mySql 数据库的一行

PHP file_get_contents foreach

MySQL 5.5 LONGBLOB 列数据对于第 1 行的列 'x' 太长

javascript - 从数组创建 pdf Blob 并查看它

php - QUickbooks PHP SDK 添加发票付款

php - MySQL 条件左连接