向/从MySQL数据库插入/查看图像 [英] Insert/view image into/from a MySQL DB
本文介绍了向/从MySQL数据库插入/查看图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在DB中插入图像时遇到问题. 该表具有以下结构:
I have a problem with inserting images in DB. The table has the following structure:
- id-> INT(3)->自动递增
- 名称-> VARCHAR(30)
- 扩展名-> VARCHAR(10)[可能太短了]
- img-> MEDIUMBLOB
插入图像的PHP代码为:
The PHP code that insert the image is:
if($_FILES['file']['error']==0){
$result = is_uploaded_file($_FILES['file']['tmp_name']);
if(!$result){
echo "Upload failed";
}else{
$type = explode("/", $_FILES['file']['type']);
$extension = $type[1];
$name = $_FILES['file']['name'];
$img = $_FILES['file']['tmp_name'];
$img = file_get_contents($_FILES['file']['tmp_name']);
$img = addslashes ($img);
}
$sql = "INSERT INTO images (name, extension, img) VALUES ('$name', '$extension', '$img')";
$result = $mysqli->query($sql);
if($result){
echo "insertion was successful";
}else{
echo "insertion failed: ".$mysqli->error;
}
这就是我尝试查看img的方法:
And this is how i try to see img:
$sql = "SELECT name, extension, img FROM images WHERE id='1'";
$result = $mysqli->query($sql);
if($result){
$a = $result->fetch_assoc();
header ("Content-type: image/".$a['estensione']);
echo $a['img'];
}else{
echo "AAAAAAAAA<hr>";
echo $mysqli->error;
}
插入没问题,但是我无法查看图像. 另外,还有另一种在Db中上传图片的方法吗?
The insertion is Ok, but i can't view the image. In addition, there's another way to upload image in Db?
推荐答案
第一个图像标签示例(您要显示结果的页面)
First in image tag example (the page where you want to display your results)
在标记中,从fetch_image_frm_db.php页面获取图像,并显示
in the tag get the image from fetch_image_frm_db.php page, and display
<img src="fetch_image_frm_db.php?id=<?php echo $id_of_row;?>"/>
fetch_image_frm_db.php页面
fetch_image_frm_db.php page
$id=$_GET['id'];
$query = "SELECT * FROM images WHERE id=$id";
$result=mysql_query($query) or die('Error, query failed'.mysql_error());
$row=mysql_fetch_array($result);
header("Content-type:image/jpeg");
stripslashes ($row['img']);
echo $row['img'];
* * 在db中存储图像不是一个好习惯
** storing images in db is not good practise
这篇关于向/从MySQL数据库插入/查看图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文