Is this a bad practice?

Red Squirrel

[H]F Junkie
Joined
Nov 29, 2009
Messages
9,211
I need to query a topics table and get the number of posts per forum that match my criteria, in my case, the number of posts that are pending approval, and by a certain member.

Code:
				$DB->query("SELECT forum_id FROM ibf_topics WHERE starter_id=".$vuid." AND approved==0");
				
				while($row = $DB->fetch_row())
				{
					$forums[$row['forum_id']+=1;
				}


                               //foreach loop to get data and do stuff with it


So to get the number of new posts for forum ID 10 for example, I would go $forums[10]; and get the number of posts that matched my query, where forum_id was 10. Now in my while loop, is it safe to assume that the first time I refer to $forums[10] that the default value will be 0 so when I do my increment it will go to 1? This cannot be initialized ahead of time since I do not know what all the forum IDs are, it does not necessarily start from 1 to nnn as forums get deleted/added over time.
 
It is in the sense that if you have error logging enabled, your log file will be full of notices about undefined offsets.
 
Yeah I found the syntax errors after, I typed it fast with intention of going back.

And the reason I'm not using count is because that would be 2 queries per forum. Instead my first query gets the number to increment by for each forum then the other queries will just add the values (and do other stuff too).

And yeah forgot about the notice thing, but I usually turn notice off. Most scripts wont run properly if it's turned on. I can see why it would be good to initialize ahead of time as it can make things easier to debug with notice turned on.
 
Can't you use joins to get the count for all forum topics in a single query?
 
And the reason I'm not using count is because that would be 2 queries per forum. Instead my first query gets the number to increment by for each forum then the other queries will just add the values (and do other stuff too).

I don't see that you're selecting enough in the SQL you posted in the first post to be able to do anything but do a count, since you're only selecting forum_id. Plus you can accomplish the count with one query across all forums with something like this:
Code:
SELECT forum_id, count(forum_id) as pending_count FROM ibf_topics WHERE starter_id=".$vuid." AND approved==0 group by forum_id
 
I don't see that you're selecting enough in the SQL you posted in the first post to be able to do anything but do a count, since you're only selecting forum_id. Plus you can accomplish the count with one query across all forums with something like this:
Code:
SELECT forum_id, count(forum_id) as pending_count FROM ibf_topics WHERE starter_id=".$vuid." AND approved==0 group by forum_id

Hmmm yeah I forgot about grouping. I'm a little rusty on sql. That is another better option for me. the more I can do at the sql level, the faster the script will execute, somewhat.
 
Back
Top