如何从mysql数据库中显示图像?

时间:2017-03-04 12:16:16

标签: php html mysql

这是我的mysql表crij_personne的结构:

  • id
  • photo longblob
  • image_name varchar(64)

我的html代码如下:

<input type="file" name="photo" />

将图像上传到我的数据库的代码:

$imagetmp=addslashes (file_get_contents($_FILES['photo'] ['tmp_name']));
$image_name = addslashes($_FILES['photo']['image_name']);
$imagetmp= base64_encode($imagetmp);
$sql = "INSERT INTO crij_personne (description, photo, image_name) VALUES ('".$_POST['description']."','$imagetmp',' $image_name');"; 
if (mysqli_query($conn, $sql)) {
        echo "New record created successfully";
} else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
        }

在网页上显示图像的代码是:

echo '<img height="300" width="300" src="data:image;base64, '.$row['photo'].'">';

但是没有发生任何事情......显然,我做错了什么。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

试试这个。

用于将值插入数据库。

$image_name = addslashes($_FILES['photo']['image_name']);
$sql = "INSERT INTO crij_personne (description, photo, image_name) VALUES ('".$_POST['description']."','$imagetmp',' $image_name');";

if (mysqli_query($conn, $sql)) echo "New record created successfully";
else echo "Error: " .  mysqli_error($conn);

从数据库中检索图像

$connectDb = mysqli_connect("localhost","root","password","DatabaesName"); //You need to replace with your own credentials 
$query= "SELECT * FROM crij_personne WHERE id = $id";
$sth = $connectDb ->query($query);
$mysqli_fetch_array=mysqli_fetch_array($sth);
header("Content-type: image/jpeg");
echo '<img src="data:image/jpeg;base64,'.base64_encode( $mysqli_fetch_array['image_name'] ).'"/>';

然后检索,我希望你能得到正确的输出。