简体   繁体   中英

Display image from database showing same images

I am trying to display an image coming from the database and I was able to get it but the problem is, it's displaying same images even though I uploaded different images.

Here's my code:

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

Pls. help me...

Your problem is the getImage.php does not return the corresponding image with id in query string. Your source codes always return the image of latest news, right?

Try to replace this :

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

to

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

Because I'm lazy, I'm going to assume id is numeric here.

In getImage.php :

We need to tell getImage.php to just get the image that has the ID we want.

$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";

As it is now, getImage.php is actually outputting all your images. You only see the one with the latest date however. This is because it's the first retrieved by your script thanks to the ORDER BY clause.

Also, in your display loop, change this:

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

to this:

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

Removed the extra single quote between id= and it's number, this way the number will actually be sent to your script.

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