Hi!
Im a noob to PHP but had to use it instead of ASP because I couldn't retrieve images from database using ASP + MS Access... Anyways.. I have couple questions:

Number 1: How to retrieve and displaymultiple(!) images(jpg) from mysql DB?

NUmber 2: I have a main page that displays iframe with multiple images (they are hardcoded for now). When pressing on any image it will redirect to a page with that image and text box for a comment..(thats the plan anyway) . And is it possible to disable redirect option if the user is not logged in (based on cookie)?

<div class="img">
 <a target="_blank" href="klematis_big.htm"><img src="1.jpg" alt="Klematis" width="220" height="130" /></a>

</div>
<div class="img">
 <a target="_blank" href="klematis2_big.htm"><img src="2.jpg" alt="Klematis" width="220" height="130" /></a>
 </div>

<div class="img">
 <a target="_blank" href="klematis3_big.htm"><img src="3.jpg" alt="Klematis" width="220" height="130" /></a>
</div>
<div class="img">
 <a target="_blank" href="klematis4_big.htm"><img src="4.jpg" alt="Klematis" width="220" height="130" /></a>
</div>
<div class="img">
 <a target="_blank" href="klematis4_big.htm"><img src="5.jpg" alt="Klematis" width="220" height="130" /></a>
</div>
<div class="img">
 <a target="_blank" href="klematis4_big.htm"><img src="6.jpg" alt="Klematis" width="220" height="130" /></a>
</div>
<div class="img">
 <a target="_blank" href="klematis4_big.htm"><img src="7.jpg" alt="Klematis" width="220" height="130" /></a>
</div>
<div class="img">
 <a target="_blank" href="klematis4_big.htm"><img src="8.jpg" alt="Klematis" width="220" height="130" /></a>
</div>
<div class="img">
 <a target="_blank" href="klematis4_big.htm"><img src="9.jpg" alt="Klematis" width="220" height="130" /></a>
</div>
<div class="img">
 <a target="_blank" href="klematis4_big.htm"><img src="10.jpg" alt="Klematis" width="220" height="130" /></a>
</div>

Thanks

Hi,

In response to question 1, you have two options here. First is storing the images as BLOB(which I don't really recommend, unless you have a superly expensive copyrighted images.) , second, just have the image filename stored in database.

Say you have a database called image, and this image table have the following columns id, name, status, access. Simple explanations of columns: id is set to auto-increment, name is for the filename e.g. somejpg.jpg, status can be set to true or false, and finally access can be set to public or private.

Using the above image's parameters, we can then build our database query based on those columns. e.g. select from image where status='true' (this pull out all of the images with the status set as true).

For question two, You don't have to use iframe for this type of application, you can just send query to the database and just iterate the results, thus showing these results on the page.. Again I am assuming here that you already have a database setup for your members, and a login system to validate your users.

Depending on your login system validation for members logged in or not.., we can use a query based on this validation like

 if ($loggedIn){
 ## we make the image href url live
 echo '<a href="locationOfYourImages/'.$row['name'].'.jpg"><img src="locationOfThumb"/></a>';

 }
 else{
 ## show thumbnail without link

 ## if you allow the public to view sample images, just to intice prospective new members

 ## you can then show links here for the public 
 }

Don't forget to protect your images dirctory from public access.. this can be done with simple .htaccess ..

To insert your exsiting images info. to your database, you need to read the image directory using php script, and then load items inside the form, where you can further edit the info. e.g. name, access, status..etc.. etc..

Summary of tasks needed.
1. Find a good login script. this is freely available all over the Internet.. You can search my previous post two days ago. I have some really good recommendation on login script off from sourceforge.
2. Create database table for your images,. for the members, the instruction is already covered in the script read me file.
3. This we need to discuss later. this is pretty lengthy..

Thanks for reply!
Let's see.....
I have login function - works fine, at leats so far :-)..
I have set up database with tables : users, images, admin and comments..
Images table has ID, Image itself, UserID(who uploaded that), Status and Date(Uploaded). I store images as BLOB
(I'd try to store as a link to the file with images but I've no idea how to do that and i've no much time left to investigate. I was trying to achive that using ASP and MS Access but just wasted huge amount of time. So I had to go for PHP + MySQL and hope for a miracle to finish in time)
...Anyway.. I've managed to retrieve and display one image. but I need them all on one page and then I will insert that page into an iframe on the main page...That's the plan..
About the thumbnails without the link... Thanks! Silly me! I should've guessed myself....

If we want the page containing the images to be inserted in an iframe, then you can create the page dynamically..or write a simple php function to retrive the images data from the database and call it within the iframe.

example of dynamically created page. Let's say, we have a page called iframecontents.php.. this is the file that will be called by the iframe ... e.g.

<iframe src="iframecontents.php"></iframe>

Let's make sense out of the iframecontents.php..

  ## filename : iframecontents.php

  ## normally, I get pretty lazy this time of the day, but I am fighting for it as much as I could, let us write a simple function. I want it reusable at any page if needed be.

  function show_images($sql){
  ## define all of your database credentials below
  $db = "someDb";
  $db_host = "localhost";
  $db_user = "someUser";
  $db_pass = "somepassword";


  ## let's connect to database..
  $connect = mysql_connect($db_host,$db_user,$db_pass) or die(mysql_error());
  $db = mysql_select_db($db,$connect)  or die(mysql_error()); 
  $result = mysql_query($sql, $connect) or die(mysql_error()); 

  ## now that we are connected we can loop through the result

  while($row = mysql_fetch_array( $result )) 
  {
  $data[] = $row;
  }
  ## we return the data

  return $data;

  }  
  ## end of our little function

  ## code below is responsible for generating the actual result given by query..

  ## define the query
  $query = "(SELECT * FROM images )"; 

  ## call the function above
   $data = show_images($query);
    ## iterate through the results returned by the function 
   foreach($data as $images ){
      ?>
      <p><a href="location"><img src="<?=$images['imageItself']?>" width = "100" height="100"/></a>
      <br/>
       </p>
   <?php
   }


  ?>

The images should be showing in the iframe... Please let me know if there are any errors on the page. I just typed in the codes here, while my mind is trying to make this up, with sense of course, and never have the chance to test it.

I've tried this:

<?php
  function show_images($sql){
  ## define all of your database credentials below
   include "file_constants.php";
  ## let's connect to database..

  $connect =  mysql_connect("$host", "$user", "$pass")or die("cannot connect"); 
  $db = mysql_select_db("$db_name")or die("cannot select DB");
  $result = mysql_query($sql, $connect) or die(mysql_error()); 

  ## now that we are connected we can loop through the result
  while($row = mysql_fetch_array( $result )) 
  {
  $data[] = $row;
  }
  ## we return the data
  return $data;
  }  
  ## end of our little function
  ## code below is responsible for generating the actual result given by query..
  ## define the query
  $query = "SELECT Image FROM images;";

  ## call the function above
   $data = show_images($query);

    ## iterate through the results returned by the function 
   foreach($data as $images )



   {
      ?>
      <a href="location"><img src="<?=$images['imageItself']?>" width = "100" height="100"/></a>
   <?php
   }
  ?>

....aaaaand I'm getting 5 small icons...like RGB icons.. Looks like it can find them in DB but having problem displaying it...Faced the same result with MS Access...

Can you put up the snippet of your codes repsonsible for inserting image as blob? This has to be binary.. Just hold on let me write a simple script that will do this... I think we need to add header type .. Let try this first.

change this

 foreach($data as $images )
 {
 ?>
<a href="location"><img src="<?=$images['imageItself']?>" width = "100" height="100"/></a>
<?php
}

to this

 foreach($data as $images )
 {
 $img = $images['imageItself'];
 header('Content-type: image/jpg');

 ?>
<a href="location"><?=$img?></a>
<?php
}

What we are trying to achieve with the modified codes is to show images in their actual size. I also use the header php function. This may work... please let me know so that I can continue writing a demo if it does not work..

Tried..No luck..
I've inserted images manually....Don't know if it affects the way it works.
However I have a code that works with one image:

<?php

include "file_constants.php";

mysql_connect($host, $user, $pass, $db_name) or die("Can not connect to database: ".mysql_error());

mysql_select_db($db_name) or die("Can not select the database: ".mysql_error());



$query = mysql_query("SELECT Image FROM images ");
$row = mysql_fetch_array($query);
$content = $row['Image'];

header('Content-type: image/jpg');


     echo $content;


?>

ok, hold on let me write a working demo script for you to use.. including upload script.. I wrote something like this long time ago. It is in my hard. I just need to find it and set it up for live server.. Wait for a few minutes...

Thats another code... when using it getting one big image ..

<?php
     include "file_constants.php";

     $link = mysql_connect("$host", "$user", "$pass")
     or die("Could not connect: " . mysql_error());

     mysql_select_db("$db_name") or die(mysql_error());

     $sql = "SELECT Image FROM images ";

     $result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
     $x=array($result);

     foreach ($x as $images)
 {

     header("Content-type: image/jpeg");
     echo mysql_result($result, 0);
 }


?>

Ok.. let's modify this one again . Sorry, it took me a while... my wireless keyboard ran out of battery. I need to recharge...

foreach($data as $images )
 {
 $img = $images['imageItself'];
header('Content-type: image/jpg');
 ?>
 <a href="location"><?=$img?></a>
<?php
 }

Change the above code to this

foreach($data as $images )
{


?>
<a href="view.php?id=<?=$images['id']?">View this image.<?=$images['id']?></a>
<?php
}

Then we can create a file view.php using your own codes above to show single image

 ## filename view.php
 ## add your database configuration file here

 if(isset($_GET['id'] && (!empty($_GET['id'])){
 $query = mysql_query("SELECT * FROM images WHERE id='".$id."'");
 $row = mysql_fetch_array($query);
 $content = $row['image'];

 header('Content-type: image/jpg');
 echo $content;
 }
 else{

 //do nothing this is just a test
 }

I set it up on my localhost like that and it is working... If it works for you, we just to make thumbnails so that you can use the thumbnails from the thumbnail directory as links..

ADDED LATER: I attempted to generate thumbnails from the blob . It was successfull, BUT it is using tremendous amount of memory. My test images sizes are 1mb, 2mb, and 10mb. For a much bigger database.. this will cause the mysql server to ran out of memory...I am running it on 16GB localhost. server type apache ->xampp on ubuntu..hard drive installed and not portable..

Some mess on line 74 ..can't get my head round after 24 hours in front of pc..

?>
<a href="view.php?id=<?=$images['id']?">View this image.<?=$images['id']?></a>
<?php
}

What are those id s ($images['id']) ? It tells me : Notice:undefined index: id and points to the line above....10 times..
is there any way to run the code without them?

Images table has ID, Image itself, UserID(who uploaded that), Status and Date(Uploaded). I store images as BLOB

That refers to the id column of your images table. I use it, because you said you have an image table with id.. just replace it with whatever you have e.g. ID.. the view.php will use this id to send query to your database and show the single image.

I set up the query to pass the result $row into array $data[], then we loop this as $images. This is a good approach, especially if you will be separating the logic of your application from view. By setting it up like that, we can easily use any templating system that will come to mind at a later time. Setting it up with..not too much html mixing with the php codes. Mixing them in uncrotrolled proportion, will create problems in maintaining your application.

Because we are using php without the benefit the of any templating system, it is difficult to use the dot notation e.g. images.id . Templating system can easily achieve this, but that is out of the scope of this topic. It is nice to have the database connection be included in a simple function, so that if some time later, you need to re-write everything into simple class, the output of the query is already inside of a function. All you have to do is define the properties , and this simpe function is still in good shape working with the other methods transparently .

Ok!
Thanks!
.....I've tried that but still getting errors:

Notice: Undefined index: ImageID in C:\xampp\htdocs\gal.php on line 37
View this image.
Notice: Undefined index: ImageID in C:\xampp\htdocs\gal.php on line 37
Notice: Undefined index: ImageID in C:\xampp\htdocs\gal.php on line 37
View this image.
Notice: Undefined index: ImageID in C:\xampp\htdocs\gal.php on line 37
Notice: Undefined index: ImageID in C:\xampp\htdocs\gal.php on line 37
View this image.
Notice: Undefined index: ImageID in C:\xampp\htdocs\gal.php on line 37
Notice: Undefined index: ImageID in C:\xampp\htdocs\gal.php on line 37
View this image.
Notice: Undefined index: ImageID in C:\xampp\htdocs\gal.php on line 37
Notice: Undefined index: ImageID in C:\xampp\htdocs\gal.php on line 37
View this image.
Notice: Undefined index: ImageID in C:\xampp\htdocs\gal.php on line 37

those are like active links, but when I press on any of the id displays first image of the DB...

It's getting really late in my time zone .. not late it is already early in the morning,,, I'll just give you the files I have created in my localhost, before I head up for scholl in about 6 hours from now. I'm going to pick up a short snooze...

It includes upload capability, insert and retrieve to and from database as blob, then confirmation page where the uploaded file can be viewed as blob..

If I don't run out of time, I will also give you the blob thumbnails function I used for testing. Although I don't recommend using this function, because it is using too much memory I think people in this community deserve to see how it can be done..Just make sure you have the GD support enabled on your xampp, before attempting to run this script.

be right back later for this thread......my starbucks energy is slowly fading away....

Ok! No problem...That's gr8 .. You've helped me a lot. Thanks!

Ok guy,

Here we go.. obviously I over slept up to the point where my professor sent someone in my dorm to wake me up.

I will just paste it here so that if other people may find this post useful, for whatever it's worth.....Ready?

Step One: In your htdocs directory, create a new directory called blob, inside the blob directory create another and name it uploads, and the rest are simple as copy and pasting. Copy sql below to create a new database table and name it "test". You are welcome to add more columns to your need.

 CREATE TABLE IF NOT EXISTS `images` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `image` longblob NOT NULL,
 `thumb` varchar(100) COLLATE latin1_general_ci NOT NULL,
 `title` varchar(255) COLLATE latin1_general_ci DEFAULT NULL,
 PRIMARY KEY (`id`)
 ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci ;

The above sql is pretty common, with one EXEMPTION.. I used longblob. This will allow you to upload or store bigger files at least 3-5mb.

Step Two: Create a file named settings.php..actually this is just the database credentials file. pretty basic

 <?php
 ## filename settings.php
 $user = "root";
 $pass = "";
 $host = "localhost";
 $db_name = "test";
 ?>

Step Three: Create a new file called function.php

 <?php
 ## filename: function.php
 ## simple class
 function simple_func($sql){
 ## define your database connection credentials
 include 'settings.php';

$conn = mysql_connect($host,$user,$pass) or die(mysql_error());
$db = mysql_select_db($db_name,$conn)  or die(mysql_error()); 

$result = mysql_query($sql, $conn) or die(mysql_error()); 
## we check and make sure we are getting a result >0
if(mysql_num_rows($result)>0) {

## And we display the results 
while($row = mysql_fetch_array( $result )) 
{
  $data[] = $row;
 }
## we return the data

 return $data;

}
 else{

## no result will be shown by the page calling this function..
 //echo '<br/>No Result to show';

}
}

Step Four: We create the show.php.. in my response last night we called it view,

<?php
## filename show.php
include'settings.php';

mysql_connect($host, $user, $pass) or die("Can not connect to database: ".mysql_error());
mysql_select_db($db_name) or die("Can not select the database: ".mysql_error());

if(isset($_GET['id']) || !empty($_GET['id'])){
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM images WHERE id='".$id."'");
$row = mysql_fetch_array($query);
$content = $row['image'];

header('Content-type: image/jpg');
echo $content;

}
else{
 echo "please select image";
 }

Step Five: We create the file called insert.php. This file will be the upload form processor...at the same time will be responsible in gerating the thumbnails.

<?php
include 'thumbfunction.php';
include 'settings.php';
$connect = mysql_connect($host, $user, $pass)or die("cannot connect");
$db = mysql_select_db($db_name)or die("cannot select DB");

## define image extension allowed
$allowedX = array('jpg', 'gif', 'bmp', 'png') ;

## define thumb widht and height
$tWidth = 100;
$tHeight = 100;
## make sure file is uploaded
if (isset($_FILES['img']) && $_FILES['img']['size'] > 0) { 

  ## this is the temp file by default locate in th tmp directory of your server
      $tmpImage  = $_FILES['img']['tmp_name']; 
      ## we define our thumb file name
      ///$filename = strtolower(str_replace(' ','_'($_POST['title'])));
       $filename =($_FILES['img']['name']);
       $ext = substr($_FILES['img']['name'], strrpos($filename, '.') + 1);

       ## we match the extension
       $title = $_POST['title'];
       $thumbname = strtolower(str_replace(' ','_',($_POST['title'])));

      ## we need to read the image file from temp directory
      $readImg      = fopen($tmpImage, 'r');
      ## image is read as binary data
      $imgBin = fread($readImg, filesize($tmpImage));
      $imgBin = addslashes($imgBin);
      ## close done reading the image data as binary
      fclose($readImg);


      ## lets prepare our query
      $query = "INSERT INTO images ";
      ## we insert image as binary blob
      $query .= "(image,thumb,title) VALUES ('".$imgBin."','".$thumbname."','".$title."')";
      $results = mysql_query($query, $connect);
      $id = mysql_insert_id();

      ### ! IMPORTANT assign sleep accordingly this helps the script to store image in database, before moving the file in the uploads directory.
sleep(10);

## if you don't need to create the thumb remove code below
## generate thumb 
      @move_uploaded_file($_FILES['img']['tmp_name'], "uploads/".$thumbname.".".$ext); 
      ## create thumbnail
      createThumb($thumbname.".".$ext, $tWidth, $tHeight, 'uploads/', 'uploads/', $thumbname.".large.jpg") ;
      ## check if the thumb exist..then delete uploaded big image
      if (file_exists("uploads/".$thumbname.".large.jpg")) {
       ## we don't need the original file because it is already in the blob
       unlink("uploads/".$thumbname.".".$ext);
       }

## of thumb generation

echo '<p><img src="uploads/'.$thumbname.'.large.jpg"/><br/><a href="show.php?id='.$id.'">image '.$_POST['title'].'</a></p>';

}else{

}

?>  

!important about this file.. I was running this script last night and even until early in the morning today. I was observing on how long would it take for the script to insert the binary image data into mysql..what I have found out that it takes a few seconds to do it with bigger images. So, I decided to give the script an sleep time of 10 seconds. Of course, you can freely adjust this to your needs. Once you see that the bigger images are not fully stored as blob, then that is the right indication for the sleep time to go up. The script also creates a well formed thumbnails. The file responsible for it is up next below..

Step Six: We create the file name called thumbfunction.php . I took this out from my open source application which I developed with my older brother Michael. Obviously, gd is not know in making a high quality images.

<?php
## filename thumbfunction.php
function createThumb($name, $maxW, $maxH, $image_path, $thumb_path, $outname) {

    $ext = substr($name, strrpos($name, ".") + 1) ;
    switch (strtolower($ext)) {
        case "jpg":
        case "jpeg":
            $img = imagecreatefromjpeg($image_path.$name) ;
            $size = ResizeMath($maxW, $maxH, $img) ;
            $size[0] = $maxW ;
            $size[1] = $maxH ;
            $img2 = imagecreatetruecolor($size[0], $size[1]) ;
            imagecopyresized($img2, $img, 0, 0, 0, 0, $size[0], $size[1], $size[2], $size[3]) ;
            imagejpeg($img2, $thumb_path.$outname) ;
            return true ;
            break ;
        case "png":
            $img = imagecreatefrompng($image_path.$name) ;
            $size = ResizeMath($maxW, $maxH, $img) ;
            $size[0] = $maxW ;
            $size[1] = $maxH ;
            $img2 = imagecreatetruecolor($size[0], $size[1]) ;
            imagecopyresampled($img2, $img, 0, 0, 0, 0, $size[0], $size[1], $size[2], $size[3]) ;
            imagepng($img2, $thumb_path.$outname) ;
            return true ;
            break ;
        case "gif":
            $img = imagecreatefromgif($image_path.$name) ;
            $size = ResizeMath($maxW, $maxH, $img) ;
            $size[0] = $maxW ;
            $size[1] = $maxH ;
            $img2 = imagecreatetruecolor($size[0], $size[1]) ;
            imagecopyresampled($img2, $img, 0, 0, 0, 0, $size[0], $size[1], $size[2], $size[3]) ;
            imagegif($img2, $thumb_path.$outname) ;
            return true ;
            break ;
        default:
            return false ;
            break ;
    }
}
function ResizeMath($maxW, $maxH, $img) {
    $imageW = imagesx($img) ;
    $imageH = imagesy($img) ;
    if ($imageW <= $maxW && $imageH <= $maxH) {
        $thumbW = $imageW ;
        $thumbH = $imageH ;
    }
    else {
        if ($imageW > $imageH) {
         ## this is wide image
            $qW = $maxW / $imageW;
            $thumbW = $imageW * $qW ;
            //$thumbH = $maxW / $imageW * $imageH ;
            $thumbH = $imageH * $qW;
        }
        elseif($imageH > $imageW){
            ## we got tall image
            $qH = $maxH / $imageH;
            $thumbH = $imageH * $qH;
        }
        else {
            $thumbH = $maxH ;
            $thumbW = $maxW ;
        }
    }
    $thumbW = round($thumbW) ;
    $thumbH = round($thumbH) ;
    $thesize = array($thumbW, $thumbH, $imageW, $imageH) ;
    return $thesize ;
}   
?>

Step 7: We create our index.php file

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<title></title>
<head>
<style>
thumb{width:650px;float:left;left:2px;margin: 0 auto;}    
.thumb ul {width: 100%;float:left;}
.thumb ul li {background:url(images/loading.png) no-repeat;background-position:50px 50px;display: inline;font-family:arial;float: left; padding-right:25px;width: 130px; height:260px;} 
.catthumb ul li{width: 140px; height:200px;} 
.thumb ul li img{float: left;width:130px;height:135px;border:1px solid #ccc;padding:2px;background-color: #ebf8ff;}  
 </style>
</head>
 <body>
 <div class="thumb"><ul>
<?php
## includes files  
include 'function.php';
include 'thumbfunction.php';

$query = ("SELECT * FROM images ");
$images = simple_func($query);

if(!empty($images)){



foreach($images as $image)
{
 ?>

<li><a href="show.php?id=<?=$image['id']?>" target="_blank"><img src="uploads/<?=$image['thumb']?>.large.jpg"/> <?=$image['title']?></a></li>

<?php    
}
}
else{
 ## there is no result in the array, we let our viewers know
?>
<li>There are no images to show</li>
<?php
}
?>
</ul>
</div>
</body>
</html>

The file above is the main entry of your blob site..

Step 8: One very last file we have to make a file named add.html.. this is our upload form.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
 <body>
 <form enctype="multipart/form-data" action="insert.php" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="1024000" type="hidden">
<p>
<label>Title</label><input type="text" name="title"/>
 </p>
 <p>
<label>Select file</label>
<input name="img" accept="image/jpeg" type="file">
 </p>
 <input value="Submit" type="submit">
 </form>
</body>
</html>

UPDATED: Sorry about the typo. The file above has been updated..

This file is responsible for allowing you to upload actual image, then store it to your database. If you get unfinished upload, just adjust the max upload file in the php.ini file located in xampp/php/php.ini file.

commented: You are amazing lol. +4

You're a star ! I'll try it as soon as I can.... Thanks!!

Now I believe in magic !!!!! Thanks a lot man !! It works like a charm!! Had to make few changes but it works !!!