bigheadedd Posted November 16, 2011 Share Posted November 16, 2011 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. Quote Link to comment https://forums.phpfreaks.com/topic/251260-getting-rows-from-within-two-tablescategories/ Share on other sites More sharing options...
requinix Posted November 16, 2011 Share Posted November 16, 2011 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 } Quote Link to comment https://forums.phpfreaks.com/topic/251260-getting-rows-from-within-two-tablescategories/#findComment-1288726 Share on other sites More sharing options...
bigheadedd Posted November 16, 2011 Author Share Posted November 16, 2011 Hi, Thanks for the reply! Yes, I realized that was why it was printing the title each time, but I wasn't sure if there was a simpler way of doing this in the query level rather than in the loop. Nevermind though, thanks! Quote Link to comment https://forums.phpfreaks.com/topic/251260-getting-rows-from-within-two-tablescategories/#findComment-1288729 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.