Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display an BLOB image stored in MySql database?

I am trying to display the last 5 images uploaded to my "store" table in MySql. I'm a complete noob to PHP and databases and i've been reading a lot on how to do this but no luck.

I can store and display pictures one at a time but i'd like to be able to have a gallery of sorts to show the last 5 uploaded.

any advice or help would be greatly appreciated thanks!

p.s. I know it frowned upon to store pictures to a database like this but this project is just for practice.

index.php

<!DOCTYPE html>
<html>
<head>
<title>Project One</title>
</head>

<body>

<form action="index.php" method="POST" enctype="multipart/form-data">
    File:
    <input type="file" name="image"> <input type="submit" value="Upload">
<form>
<p />

<?php

//connect to database
(connect to server)
(select correct DB)

//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 = $_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 store VALUES ('', '$image_name', '$image')"))
        echo "Problem Uploading Image.";
    else
        {

        $lastid = mysql_insert_id();
        echo "Image uploaded. <p />Your image:<p /><img src=get.php?id=$lastid>";

        }
  }
  }

?>

<p />
<p />
<a href="http://WEBSITE.com/gallery.php"> Go to Gallery </a>
</body>

</html>

get.php

<?php

   //connect to database
    (connect to server)
    (select correct DB)

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

$image = mysql_query("SELECT * FROM store WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];

header("Content-type: image/jpeg");

echo $image;

?>
like image 361
Ktmock13 Avatar asked Nov 03 '12 23:11

Ktmock13


1 Answers

This is what I used when I wanted to do something like that... a long time ago! =P

$sql = "SELECT image FROM table WHERE cond ORDER BY xxxx DESC LIMIT 5";
$result = mysqli_query($db,$sql);
while($arraySomething = mysqli_fetch_array($result))
{
    echo "<img src='php/imgView.php?imgId=".$arraySomething."' />";
}
like image 62
Manatax Avatar answered Nov 01 '22 08:11

Manatax