php/mysql: lower the amount on queries?

Hi, basically I am trying to loop through the categories and include the items of that category from a different table. I am concerned with my current method because with a large amount of categories, there would be to many queries, is there an easier/faster way to do this?

db tables layout:

categories
id name
1 cats
2 dogs
3 birds
…and so on…

items
id name category
1 john 3
2 mary 2
3 smurf 3
…and so on…

and my php:

[php]
<?php
$data = get_result(“SELECT * FROM categories”);

		foreach($data as $row) {
			echo "<h5>".$row[name]."</h5>\n";
			$result = get_result("SELECT * FROM items WHERE category = '$row[id]'");
			
			foreach($result as $itemrow) {
				echo $itemrow[name]."<br />";
			}
		}
	?>

[/php]

hello Wazungu, use below code instead of your current code. [php] $data = get_result("SELECT items.*,categories.name as catname FROM items,categories WHERE items.category = categories.id"); foreach($data as $row) { echo $row['catname']."
"; echo $row['name']."
"; } [/php]

i hope this will helpful for you
SR

Thankyou, perfect!

hello Wazungu,

it’s nice to hear that you got perfect answer from me.
Always welcome, post more issues.

SR

Sponsor our Newsletter | Privacy Policy | Terms of Service