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

时间:2015-05-25 11:03:37

标签: 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脚本来查看图像时,我只看到小图标。有什么我想念的东西。

感谢。

1 个答案:

答案 0 :(得分:0)

使用类似的东西

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