EE Tip: Counting the results of a nested query

If you’ve built anything remotely challenging in ExpressionEngine, you’ve no doubt discovered things that are easier done in native PHP than in EE tags. A lot of it has to do with how ExpressionEngine parses templates and what gets parsed first.

One recent bugbear I ran into was trying to use the {count} magic” variable from a call to {exp:query} that resided inside a loop. I needed the {entry_id} from the entry in the SQL statement, but {count} (despite being used inside {exp:query}) was evaluating as the count and not the {exp:query} count. To solve the issue, I came up with the following:

You’ll notice I’m using {exp:query} twice. The first time is to establish a variable in the SQL connection. Then I am free to use the variable in the second query and the count (returned as {query_count}) will be a count of the inner loop instead of the outer one.

It is important to note, however, that MySQL will evaluate the variable’s incrementation before paying attention to any ORDER BY clauses, so your mileage may vary. Regardless, it’s a handy technique.

Like it? Share it

Share on LinkedIn

Share on Google Plus