Why are the terms filled when they are actually empty?
Looks to be a PHP issue and not drupal. You're not clearing your $tid_1,$tid_2,$tid_3 values within your for loop

So when $data->StkGrupKodu1 isn't set for example the value of $tid_1 is still that of the last time $data->StkGrupKodu1 did exist.

You could declare your $tid_1,$tid_2,$tid_3 variables at the top of your foreach loop so they get set similar to what you're doing if the database results null