Hi,

I am pretty new to php.

On my site, I have set up a form to store images in a database, it works fine, and the images are stored in there as BLOB files.
However, I can't work out how to display the image from the database.

I want to show the image on a page, that relates to the correct image id in the database. thats it.
Does anyone know how to do this?

Cheers,

QWaz

Recommended Answers

All 7 Replies

Hi,

I am pretty new to php.

On my site, I have set up a form to store images in a database, it works fine, and the images are stored in there as BLOB files.
However, I can't work out how to display the image from the database.

I want to show the image on a page, that relates to the correct image id in the database. thats it.
Does anyone know how to do this?

Cheers,

QWaz

You could do it this way:

<?php
if (isset($_GET['id'])) {
	$id = $_GET['id'];
	open_database();
	$result = do_query("SELECT foto,type FROM ftemp WHERE fid=".$id."");
	$num_result = $result->num_rows;
	if ($num_result <> 0) {
		$row = $result->fetch_assoc();
		switch($row['type']) {
			case 1 : header("Content-type: image/gif"); break;
			case 2 : header("Content-type: image/jpg"); break;
			case 3 : header("Content-type: image/png"); break;
		}
		echo $row['foto'];
	}
}
?>

The call to open_database() needs to be replaces with your method to open the correct database. The "do_query" function is this:

function do_query($query) {
	global $db; //handle to current open database (mysqli)
	$result = $db->query($query);
	if ($db->errno) {
		echo "<p>Error: ".$db->errno."  ".$db->error."</p>";
		echo "<p>Please contact the database administrator.</p>\n";
		exit();
	}
	return $result;
}

And this is how you call the php code from a html page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
			"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
  <p>Some text.</p>
  <div style="height:300px"><img height="300px" src="display.php?id=47" alt=""/></div>
  <p>More text.</p>
</body>
</html>

You probably don't want to put them into a db though if you can avoid it else the db is gonna get massive.

Why not store them in the filesystem?

You probably don't want to put them into a db though if you can avoid it else the db is gonna get massive.

Why not store them in the filesystem?

That is a totally irrelevant. QWaz clearly states that the images are in a blob in the database and only want to know how to display them.

Sometimes it is better to store images inside a database sometimes it is not a good idea. I did read a lot of post in this and other forums and the debate is still going on....

Only trying to voice another opinion - when I was learning PHP I found comments like that hugely useful as it allowed me to try different things. I too tried the database route for images & ended up being kicked out by my host as the db server --> web server traffic was too high.

Only trying to voice another opinion

but it doesn't solve his problem.

It depends on what kind of images you store and how much, the size in bytes of the images, the logic behind it, what is or isn't possible at the hosting party, and if I think about it I can give you a dozen of other reasons why you should or shouldn't store images inside the database.

Hey guys,

Thanks for your replies. I tried to do it the database way, but viewing the images the way I wanted to ended up being such a headache.

So i did it in a file system way.
For any one that reads this post in the future, the code that I used and that works really well is below. I hope it helps someone else.

The reason I am using this is: so I can have a news section, with a thumbnail image next to the heading -> then when the heading is clicked, the article appears on another page with the same image but in a larger size.
*NB = I am sure there is a way that I can make this better, more secure, or simplier, however it works for me.

THIS IS THE PHP / MySQL CODE TO ADD IT TO DATABASE AND FILE.

require_once('../includes/admin/db.php'); // database connection
	$conn = dbConnect('admin'); // Connection type


        $OK = false;
	$done = false;
	
	$user = $_GET['user']; // These are for my site, cause I needed them
	$team = $_GET['team'];
	$team = str_replace(" ","+",$team);



 
if (array_key_exists('publish', $_POST)) {
    try    {
/*** check if a file was uploaded ***/
if(is_uploaded_file($_FILES['newsPhoto']['tmp_name']) && getimagesize($_FILES['newsPhoto']['tmp_name']) != false) {
			$maxsize = 2000000;
   
	if($_FILES['newsPhoto']['size'] < $maxsize ) {
	
    	/***  get the image info. ***/
    	$size = getimagesize($_FILES['newsPhoto']['tmp_name']);
		
    	/***  Assign Variables. ***/ // These variables will need to be applied to what you are doing..
		$uploadDir = "../images/photos/"; // Needs to come from the place where the file is being sent from. ALSO needed to set up the: upload_tmp_dir = to point towards this folder. THIS IS DONE IN "php.ini" FILE. THIS NEEDS TO BE REDONE WHEN THE SITE GETS UPLOADED TO SERVER.
		$timeStamp = time();  // This makes sure that all images have a unique name and there are no images with the same name. 
		$user = $_GET['user'];
		$id = NULL;
		$team = $_GET['team'];
		$team = str_replace(" ","+",$team);
		$heading = $_POST['heading'];
		$article = $_POST['elm1'];
		$photo = $_FILES['newsPhoto']['tmp_name'];
		$name = $_FILES['newsPhoto']['name'];
		$name = $timeStamp.$name;
		$filePath = $uploadDir . $name; 
		$type = $size['mime'];
		$size = $size[3];
 
    	/***  check the file is less than the maximum file size ***/
  
		/// Upload the file to the folder
		$result = move_uploaded_file($photo, $filePath);
		if (!$result) {
		echo "Error uploading file";
		}

		
		/*** connect to db ***/
		$conn = dbConnect('admin');

		/*** set the error mode ***/
		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		/*** our sql query ***/
		$done = $conn->prepare("INSERT INTO news (id, team, heading, article, photo_file_name, photo_type, photo_size) VALUES (?,?,?,?,?,?,?)");
 
		/*** bind the params ***/
		$done->bindParam(1, $id);
		$done->bindParam(2, $team);
		$done->bindParam(3, $heading);
		$done->bindParam(4, $article);
		$done->bindParam(5, $filePath);
		$done->bindParam(6, $type);
		$done->bindParam(7, $size);

		/*** execute the insert ***/
		$done->execute();
			
		
        }
    else
        {
        /*** throw an exception is image is not of type ***/
        throw new Exception("File Size Error");
        }
    }
else
    {
    // if the file is not less than the maximum allowed, print an error
    throw new Exception("Unsupported Image Format!");
    }
}
    catch(Exception $e)
        {
        echo '<h4>'.$e->getMessage().'</h4>';
        }
    }
       /// If this all works, it will show a blank page for 1 sec, then redirect them back to where the url points them to.
	if ($done) {
		header ("refresh:1;url=news.php?user=$user&team=$team");
		echo 'Article is being published, You\'ll be redirected in about 1 secs. If not, click <a href="url=news.php?user=$user&team=$team">here</a>.';	
		exit;
	}
	// display error message if query fails
	if (isset($update) && !$OK && !$done) {
			$error = $update->errorInfo();
			if (isset($error[2])) {
				echo $error[2];
			}
	}

THIS IS THE HTML CODE

<form method="post" title="" name="newsNew" id="newsNew" enctype="multipart/form-data" >


		<h3>Heading</h3>

		<input type="text" name="heading" class="headingText" id="heading" value="" title="" maxlength="60" />
		
		<h3>Article</h3>
			<textarea id="elm1" name="elm1" rows="15" cols="80" class="textEditor" >
			</textarea>
		<h3>Photo</h3>
		<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
      	        <input type="file" name="newsPhoto" id="newsPhoto" value="" />

	

		<br />
   
        <input type="submit" class="publishButton" id="publish" value="Publish News" title="" name="publish" />

</form>

THIS IS THE PHP / MySQL CODE TO VIEW THE IMAGE

$user = $_GET['user'];
	$team = $_GET['team'];
	$team = str_replace(" ","+",$team);
	$id = $_GET['id'];


$sql = "SELECT * FROM newsnew WHERE id='".$id."'";
// Fetch the columns from the database 
foreach ($conn->query($sql) as $row) { 
		$setHeading = $row['heading'];
		$setArticle = $row['article'];
		$setFileNamePath = $row['photo_file_name'];
		
}

THIS IS THE HTML CODE TO VIEW THE IMAGE

/// The image src is taken from the database and the name of the image has a timeStamp in front of the name of the image as defined in the first php code in variable $timeStamp. This makes sure that each image name is different, just in case the image has the same name as another image.  
		<h3>Current Photo as Thumbnail</h3>
		<img src="../images/photos/1272011705blog.jpg" width="150" height="150"/>
        
		<h3>Current Photo for Article</h3>
		<img src="../images/photos/1272011705blog.jpg" width="350" height="350"/>

I hope this helps someone, and saves them the 6 hrs it took me to work this out. :)

if anyone has an improvement on my code, I'm open to improvement.

Cheers,

QWaz

This tread seems solved then. Using my code for those who have there images stored in a database and using QWaz method if you store them in folders.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.