0

Hi im new to php and html. im trying to make a page for my first site where one can view all the comments posted on the site. these comments have image attachment. all the info is stored in a mysql database.

ive created a while loop to echo out every comment and image after each other. the text and the username gets updated correctly in each loop cycle but all the images are the same (the last picture loaded). i've been trying to figure it out but can't..

while($query_row = mysql_fetch_assoc($query_run))
{

$username = $query_row['username'];
$comment = $query_row['text'];
$id = $query_row['id'];
$image = $query_row['image'];

$_SESSION['comment_image'] = $image;

echo "Comment by <strong>$username</strong><br>";
echo $comment.'<br>';


echo '<img src=get_image.php><br>';
}

get_image.php:

session_start();

$image = $_SESSION['comment_image'];
header('Content-type: image/jpeg');

echo $image;

output:

Comment by USER1
text1
image3

Comment by USER2
text2
image3

Comment bu USER3
text3
image3

So the problem is that image3 gets echoed out on each comment when it should be image1 then image2 then image3, and so on. the image seems to be the one from the last comment shown.

b00n
  • 135
  • 5

2 Answers2

1

stop using blobs, storeing the image file name\path in the db is a lot easier.. but if you have no options ..

change

echo '<img src=get_image.php><br>';

to

echo '<img src="get_image.php?'.id=$id.'" />';

change get_image.php so something like this:

<?php
$id = (isset($_GET['id']) && is_numeric($_GET['id'])) ? intval($_GET['id']) : 0;
$image = image_from_db($id); // what ever you use to query the db

header('Content-Type: image/jpeg');
echo $image;
?>
0

To output the image when you output the tag, instead of linking to another script to output the image, add the following funciton, and call it from your loop with your image variable.

(From answer here - php: recreate and display an image from binary data)

function data_uri($contents, $mime) 
{  
    $base64   = base64_encode($contents); 
    return ('data:' . $mime . ';base64,' . $base64);
}

...

echo '<img src="' . data_uri($image,'image/jpeg') .'"><br>';
Community
  • 1
  • 1
jantzl
  • 136
  • 6
  • No that doesn't work. that just outputs the text info of the image. just a bunch of random chars. I've tried – b00n Oct 20 '13 at 20:04
  • Oh I understand now. You have the binary content of the image in the variable. – jantzl Oct 21 '13 at 19:44
  • The updated solution eliminates the need for another script and another call to the database, since you already have the image data in the loop where you create the image tag. – jantzl Oct 21 '13 at 19:51