Im testing your code, and i find something wrong, or perhaps i making wrong something. In a funcion count_categories you count like :
WHERE position LIKE '".$thisPosition.">%';
and if you echo $sql return:
WHERE position LIKE '68>86>>%';
i think there are a entra ">". It's posible ?