图像上传到mysql数据库但不会在我的网站上生成

时间:2015-11-24 11:52:25

标签: php mysql image mysqli phpmyadmin

这是上传我的图片的代码,还包含显示它的img标记

// imgposttest.php      
<html>
        <form method="POST" enctype="multipart/form-data">
    <input type="file" name="image"/>
    <input type="submit" name="upload" value="upload"/>
    </form>

        <?php
    include('blogconnect.php');
    include('header.php');
        if(isset($_POST['upload']))
        {

            $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($_FILES["image"]["type"] == "image/jpeg" || $_FILES["image"]["type"] == "image/png") {
            echo "Working code";
            mysql_query("INSERT INTO pics (img, imgname) VALUES ('$imagedata', '$imagename')"); 
        }
        }
        ?>
        <img src="get.php?id=1"/>
        </html>

这是假设正确生成图像的代码

// get.php

<?php
include('blogconnect.php');
if(isset($_GET['id'])){
$id = mysql_real_escape_string($_GET['id']);
$query = mysql_query("SELECT * FROM pics WHERE id=$id");
while($rows = mysql_fetch_assoc($query)){
$imagedata = $rows['img'];
}
header("content-type: image/jpeg");
echo $imagedata ;
}
?>

我已连接到数据库,并认为问题出在get.php

2 个答案:

答案 0 :(得分:1)

在get.php中

$query = mysql_query("SELECT * FROM pics WHERE id=$id"); 

放置并查看是否打印任何数字

echo $query->num_rows;

答案 1 :(得分:0)

您不应再使用mysql扩展名,因为它已被标记为已弃用。我用mysqli重写了代码。这是我的工作示例:

<强> imgposttest.php

<html>
    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="image"/>
        <input type="submit" name="upload" value="upload"/>
    </form>

<?php
    //include('blogconnect.php');
    //include('header.php');
    $mysqli = new mysqli('localhost', 'root', '', 'my_db');
    if(isset($_POST['upload']))
    {
        $imagename = $mysqli->real_escape_string($_FILES["image"] ["name"]);
        $imagedata = $mysqli->real_escape_string(file_get_contents($_FILES["image"] ["tmp_name"]));
        $imagetype = $mysqli->real_escape_string($_FILES["image"] ["type"]);

        if($_FILES["image"]["type"] == "image/jpeg" || $_FILES["image"]["type"] == "image/png") {
            echo "Working code";
            $mysqli->query("INSERT INTO pics (img, imgname) VALUES ('$imagedata', '$imagename')"); 
        }
    }
?>
    <img src="get.php?id=1"/>
</html>

<强> get.php

<?php
//include('blogconnect.php');
if(isset($_GET['id'])){
    $mysqli = new mysqli('localhost', 'root', '', 'my_db');
    $id = $mysqli->real_escape_string($_GET['id']);
    $query = $mysqli->query("SELECT * FROM pics WHERE id=$id");
    while($rows = $query->fetch_assoc()){
        $imagedata = $rows['img'];
    }
    header("content-type: image/jpeg");
    echo $imagedata ;
}

确保已将数据库中的字段设置为二进制(BLOB - 二进制大对象)。另外,检查文件是否有意外输出,空白或任何其他输出导致无效 - 在此示例中不显示图像。

真诚地