The template vb:each function is one of those where I always wonder why it even exists.
You need to parse your results into an array anyway so why even bother with parsing it a second time in the template? Just generate the lines in a template with each pass in PHP.
Anyway, in your PHP code get your results into an array using either a for each or a while. Then pass the results to the template. Or maybe even just pass the query results to the template...
Code:
$templater->register('referrals', $referrals);
(NOT SURE if that will work or not. I think the array with a consecutive itemid for the $key may be needed.)
Then parse it in the template...
Code:
<vb:each from="referrals" key="referrerid " value="referral">
Your template code using {vb:raw referral.whatevervalueneeded}
</vb:each>