Multiple queries in loop

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bookwalla
Forum Newbie
Posts: 1
Joined: Mon Jun 07, 2010 6:01 pm

Multiple queries in loop

Post by bookwalla »

Hi,

I am quering mysql database to get the name of an image, and then attaching the name of the image to a list tag. this way I can poplulate the list with images dynamically:
<?php
$query = "SELECT filename from files";
$result = db_query($query);

print "<ul>";
{
while($row=db_fetch_array($result))
{
$filename = $row['filename'];


print "<li><a href=\"/sites/mysite.com/files/$filename\" class=\"01\"><img src=\"/sites/mysite.com/files/$filename\" /></a></li>\n";
}
}
print "</ul>\n";
?>

The above code works fine, but I also want to add an image description inside this <li>:
print "<li><h1>$description</h1><a href=\"/sites/mysite.com/files/$filename\" class=\"01\"><img src=\"/sites/mysite.com/files/$filename\" /></a></li>\n";

So each image in a list item will also have a description.
The problem is that the description of the image is in a completely different table in the database: SELECT description from upload

So how do I make this happen for the description part. the filename php is working good.
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Multiple queries in loop

Post by califdon »

You Join the tables in the query, assuming that you have a foreign key in the descriptions table that identifies which primary key it refers to. It should be a one-to-one relationship. In case there might be some images for which there is no description in the other table, you would want to make it an Inner Join so that you get ALL the records from the image table, with matching descriptions if they exist.
Post Reply