0

我在上传图片时遇到了显示图片的问题。它将所有数据插入 mysql,但它们不会在本地主机上显示为预览图像。它只是显示为断开的链接。

这是我使用文件上传将图像插入数据库的代码:

<?php
error_reporting(E_ALL^E_NOTICE);

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd"
    >
<html lang="en">
<head>
    <title> Member System- Log In</title>
</head>
<body>
    <form action="register.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="image" ><br>
<input type="submit">

</form>

    <?php


    //connect to database
    mysql_connect("localhost", "root", "root") or die("mysql_error()");
 mysql_select_db("users") or die("mysql_error()");

 //file properties
$file= $_FILES['image']['tmp_name'];

 if (!isset($file))
 echo "Please select an image";
 else {
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name=addslashes($_FILES['image']['name']);
$image_size= getimagesize($_FILES['image']['tmp_name']);
 }
if ($image_size==FALSE)
echo "That's not an image.";
else {
    if (!$insert= mysql_query("INSERT INTO images VALUES ('$id','$image_name','$image')"))

    echo "Problem uploading image.";
    else {

        $lastid= mysql_insert_id();
        // create the query
//$sql = "select image from images where id=1";
// the result of the query
//$result = mysql_query($sql) or die("Invalid query: " .mysql_error());
// there should only be 1 result (if img_id = the primary index)
//$pic = mysql_fetch_array($result);
// show the image
//echo "Image uploaded. <p/> Your image: <p/> <img src='picture/".$pic['img_name']."' width='300' height='300'/>";
        echo "Image uploaded. <p/> Your image:<p /><img src=<?php get.php?id=$lastid >";


    }




 }



    ?>

Then I called get.php to retrieve the last image id from the database. Here's that code:

<?php
mysql_connect("localhost", "root", "root") or die("mysql_error()");
 mysql_select_db("users") or die("mysql_error()");

 $id= addslashes($_REQUEST['id']);

 $image= mysql_query("SELECT * from images WHERE id=$id");
 $image= mysql_fetch_assoc($image);
 $image= base64_decode($image['image']);

 ![enter image description here][1]header("Content-type: image/jpeg");
 echo $image;

?>
4

1 回答 1

0

我看到几个问题,您的图片标签看起来错字了

<img src=<?php get.php?id=$lastid >

即使更正了,HTML 页面中的标记也将是:

<img src=JFIF0[more binary data here] >

当你的意思可能是

<img src='get.php?id=<?php echo $lastid ?>' >

生产

<img src='get.php?id=3421' >

我看到的另一个问题是您在将二进制数据插入数据库之前调用了 addlashes

如前所述,您应该考虑使用 mysqli_* 系列函数来帮助防止 sql 注入。

于 2013-07-03T19:18:55.147 回答