简体   繁体   中英

PHP - Viewing all comments with image attachment, only showing last entry in database

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.

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;
?>

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>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM