【问题标题】:Display image from database showing same images显示来自数据库的图像,显​​示相同的图像
【发布时间】:2013-05-19 14:21:06
【问题描述】:

我正在尝试显示来自数据库的图像并且我能够得到它,但问题是,即使我上传了不同的图像,它也显示相同的图像。

这是我的代码:

<?php 
$con = mysql_connect('localhost','root','')
or die(mysql_error());
mysql_select_db ("dbname");

$query = "SELECT * FROM news ORDER BY date DESC";
$result = mysql_query($query);
echo "<table align='center'>";

while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>";
echo "<img src='getImage.php?id='".$row['id']."' height='230px' width='300px'> <br /><br />";   

//Some codes here...

echo "</table>";
mysql_close($con);
?> 

getImage.php

<?php 
$con = mysql_connect('localhost','root','')
or die(mysql_error());
mysql_select_db ("dbname");

$query = "SELECT * FROM news ORDER BY date DESC";
$result = mysql_query($query);

header("Content-type: image/png");
while($row = mysql_fetch_assoc($result))
{
echo $row['image'];
}
mysql_close($con);
?> 

请。帮帮我……

【问题讨论】:

标签: php database image png blob


【解决方案1】:

因为我比较懒,所以这里假设 id 是数字。

getImage.php:

我们需要告诉 getImage.php 只获取具有我们想要的 ID 的图像。

$id = intval($_GET['id']); 
//Forces $id to be numeric.  You wouldn't have to worry about doing this if
//you used prepared statements.  Like those in John Conde's links.
$query = "SELECT * FROM news WHERE `id`=$id";

就像现在一样,getImage.php 实际上正在输出您的所有图像。但是,您只会看到日期最新的那个。这是因为由于ORDER BY 子句,它是您的脚本第一次检索到的。

另外,在你的显示循环中,改变这个:

echo "<img src='getImage.php?id='".$row['id']."' height='230px' width='300px'> <br /><br />";   

到这里:

echo "<img src='getImage.php?id=".$row['id']."' height='230px' width='300px'> <br /><br />";

删除了 id= 和它的数字之间的额外单引号,这样数字实际上会发送到您的脚本。

【讨论】:

    【解决方案2】:

    您的问题是 getImage.php 没有返回查询字符串中带有 id 的相应图像。你的源代码总是返回最新消息的图像,对吧?

    尝试替换这个:

    $query = "SELECT * FROM news ORDER BY date DESC";
    

    $query = "SELECT * FROM news WHERE id = {$_GET['id']} LIMIT 1";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-24
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      • 2016-11-23
      • 1970-01-01
      相关资源
      最近更新 更多