Jump to content

Getting rows from within two tables/categories


bigheadedd

Recommended Posts

Hi,

 

So i'm having a little trouble trying to simplify some code I already have.

 

$result = mysql_query("SELECT images, cat_id FROM image_cat");

while ($row=mysql_fetch_array($result))
	{
	$cat_id=$row['cat_id'];
	echo $cat_id;
	$imgresult = mysql_query("SELECT * FROM images WHERE cat_id='".$cat_id."'");
		while ($col=mysql_fetch_array($imgresult))
			{
			echo $col['img_id'];
			}
	}

 

Okay, so this works, however i'm sure I can bring it together under one query, though i'm truly stumped as to how?

I thought I could do a simple join:

 

		$result = mysql_query("SELECT image_cat.cat_id, images.img_id WHERE image_cat.cat_id=images.image_cat");

 

This works, but repeats the image category on each loop. I could remove this via php if statements, but there must be a simpler/mysql solution.

 

If it doesn't make any sense I need to get

 

Img cat 1

-img 1

-img 2

 

img cat 2

-img 3

-img 4

 

etc etc

 

That join will give

 

img cat 1

-img 1

img cat 1

-img 2

img cat 2

-img 3

 

Hope that makes sense?? And any help would be amazing!

Thanks.

Link to comment
Share on other sites

You do understand why it's doing that, right? You're printing the title inside the loop, which means each time it runs it will print the title.

 

Track the previous title (starting with an empty string or null). If the current title doesn't match then print it.

previous title = null
for each image {
    if current title != previous title {
        print current title
        previous title = current title
    }

    rest of the loop
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.