Forum Moderators: coopster

Message Too Old, No Replies

Display image from query

         

mrnoisy

11:27 pm on Aug 9, 2005 (gmt 0)

10+ Year Member



In the query below, I may get 5 images from the database with the id of '$id'.


$query = "select * from images where id='$id'";
$result = mysql_query($query);
while($row=mysql_fetch_array($result))
{
$image = $row['image_filename'];
}

When I use the code below, only the last image displays. I want to select which one to display, for example the first or second one.


print "<img src='$image'>";

brendan3eb

4:09 am on Aug 10, 2005 (gmt 0)

10+ Year Member



your overwriting the $image variable about 5 times then. Use an array:

$query = "select * from images where id='$id'";
$result = mysql_query($query);
$k=0;
while($row=mysql_fetch_array($result))
{
$image[$k] = $row['image_filename'];
}
$selected_image = "2"; //second image
echo "<img src=$image[$selected_image] border=0>";

mcibor

9:29 am on Aug 10, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Brendan, you forgot to increment k, so you're overwritting the array as well:)

this should work:

$query = "SELECT image_filename FROM images WHERE id='$id'";
$result = mysql_query($query);

while($row=mysql_fetch_assoc($result))
{
$image[] = $row['image_filename'];
}
$selected_image = 2; //second image
echo "<img src=". $image[$selected_image] ." border=0>";//you can't have an array in quotes, you need "bla {$a['1']}"; or better to use '.': "bla ". $a['1'] ."etc..."

Best regards
Michal Cibor

FiRe

10:09 am on Aug 10, 2005 (gmt 0)

10+ Year Member



Assuming each ID is unqiue, use the mysql_fetch_row() function!

mcibor

11:31 am on Aug 10, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Fire you mix things up.

mysql_fetch_row will return an array unassociated: array('bla1','bla2','bla3')
mysql_fetch_assoc will return an array associated: array('key1'=>'bla1','key2'=>'bla2','key3'=>'bla3')
mysql_fetch_array will return both above array: array('bla1','key1'=>'bla1','bla2','key2'=>'bla2','bla3','key3'=>'bla3')
mysql_fetch_object will return object

It has nothing to do with the solution, and it doesn't matter if id is unique or not (in this case mrnoisy suggested it is not unique)

Best regards
Michal Cibor

mrnoisy

1:31 am on Aug 11, 2005 (gmt 0)

10+ Year Member



Thank you brendan3eb and mcibor, your solution worked beautifully.