PHP - 查看带有图像附件的所有注释,仅显示数据库中的最后一个条目


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

嗨,我是PHP和HTML的新手。 我试图为我的第一个网站制作一个页面,人们可以在其中查看网站上发布的所有评论。 这些注释带有图像附件。 所有信息都存储在MySQL数据库中。

我创建了一个 while 循环来回显每个评论和图像。 文本和用户名在每个循环循环中都会正确更新,但所有图像都相同(加载的最后一张图片)。 我一直在试图弄清楚,但不能。

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;

输出:

Comment by USER1
text1
image3
Comment by USER2
text2
image3
Comment bu USER3
text3
image3

所以问题是 image3 在每个评论上得到回显,而它应该是 image1 然后是 image2,然后是 image3,依此类推。 该图像似乎是显示的最后一条评论中的图像。

停止使用blob,将图像文件名''路径存储在数据库中要容易得多..但是如果您没有选择..

改变

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

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

更改get_image.php这样:

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

要在输出标记时输出图像,而不是链接到另一个脚本来输出图像,请添加以下功能,并使用图像变量从循环中调用它。

(从这里的答案 - php:从二进制数据重新创建和显示图像)

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

echo '<img src="' . data_uri($image,'image/jpeg') .'"><br>';