无法显示图像PHP

时间:2016-01-14 01:47:57

标签: php html mysql

我的问题是,当我将图片上传到数据库时,上传成功但图片没有显示。这是我的代码:

SQL文件:

CREATE TABLE `images` (`id` int(11) NOT NULL auto_increment,`name` varchar(100) default NULL,`size` int(11) default NULL,`type` varchar(20) default NULL,`content` mediumblob,PRIMARY KEY  (`id`)) ENGINE=MyISAM;

Index.php

<?php if (!empty($uploadOk)): ?>
        <div>
            <h3>Image Uploaded:</h3>
        </div>
        <div>
            <img src="image.php?id=<?=$imageId ?>" width="150px">
            <strong>Embed</strong>: <input size="25" value='<img src="image.php?id=<?=$imageId ?>">'><br>
        </div>

        <hr>
    <? endif; ?>

    <form action="index.php" method="post" enctype="multipart/form-data" >
      <div>
        <h3>Image Upload:</h3>
      </div>
      <div>
        <label>Image</label>
        <input type="hidden" name="MAX_FILE_SIZE" value="500000">
        <input type="file" name="image" />
        <input name="submit" type="submit" value="Upload"><br>
      </div>
    </form>

                    </tr>';}mysql_close();?>

image.php

<?php

// verify request id.
if (empty($_GET['id']) || !is_numeric($_GET['id'])) {
    echo 'A valid image file id is required to display the image file.';
    exit;
}

$imageId = $_GET['id'];

//connect to mysql database
if ($conn = mysqli_connect('localhost', 'username', 'pass', 'db_name')) {
    $content = mysqli_real_escape_string($conn, $content);
    $sql = "SELECT type, content FROM images where id = {$imageId}";

    if ($rs = mysqli_query($conn, $sql)) {
        $imageData = mysqli_fetch_array($rs, MYSQLI_ASSOC);
        mysqli_free_result($rs);
    } else {
        echo "Error: Could not get data from mysql database. Please try again.";
    }
    //close mysqli connection
    mysqli_close($conn);

} else {
    echo "Error: Could not connect to mysql database. Please try again.";
}   

if (!empty($imageData)) {
    // show the image.
    header("Content-type: {$imageData['type']}");
    echo $imageData['content'];
} ?>

getImage.php

<?php 
$id = $_GET['id'];
$link = mysql_connect("localhost", "username", "pass");
mysql_select_db("db_name");


$sql = "SELECT content FROM images WHERE id=$id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['content'];
?>

此代码有效。我认为SQL数据库不正确或显示图像有问题。

1 个答案:

答案 0 :(得分:0)

为了显示图像,您应该使用JavaScript中的AJAX。