I have a problem with inserting images in DB.
The table has the following structure:
id->INT(3)->autoincrement
name->VARCHAR(30)
extension->VARCHAR(10) [maybe too short]
img->MEDIUMBLOB
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;
}
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
";
echo $mysqli->error;
}
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)
in the tag get the image from fetch_image_frm_db.php page, and display
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'];
** storing images in db is not good practise