用php和mysql的树菜单

I'm trying to build a tree menu. The problem is recursion. Queries are coming from another php page with functions. However doing like that the program can't get out of while loop(like its the first time the query function called) and boom, infinite loop...

Here is code:

<?php

include ("connection.php");
include ("getQueries.php");

$brandId = 1;
$modelId = 1;
$brands = getBrands($brandId);
$models = getModels($brandId);
$motors = getMotors($brandId,$modelId);

while($row = mysql_fetch_assoc($brands)){

?>
    <ul class="nav nav-list" style="padding-top: 10%">
        <li><label class="tree-toggler nav-header"><?php echo $row['marka']; ?></label>

<?php

while($row2 = mysql_fetch_assoc($models)){

?>
    <ul class="nav nav-list tree">
        <li><a href=''#'><?php echo $row2['model']; ?></a></li>

<?php

    while($row3 = mysql_fetch_assoc($motors)){

?>
            <ul class="nav nav-list tree" style="padding-left: 15%">
                <li><a href='#'><?php echo $row3['motor']; ?></a></li>
            </ul>
<?php
    }
    $modelId++;
?>
    </ul>

<?php
}
$brandId++;
?>
</li>
    </ul>
<?php
}

And the query page:

<?php

include ("connection.php");

function getBrands($brandId){

$brands = mysql_query("SELECT * FROM araba_marka WHERE id = '$brandId'");
return $brands;
}

function getModels($brandId){

$models = mysql_query("SELECT * FROM araba_model WHERE marka_id = '$brandId'");
return $models;
}

function getMotors($brandId,$modelId){

$motors = mysql_query("SELECT * FROM araba_motor WHERE marka_id = '$brandId' AND model_id = '$modelId' ORDER BY motor ASC");
return $motors;
}

Edit: Infinite loop problem has been solved. But now by getting queries just once(at the beginning, not like parameters), there is a new problem. If there are 2 or more elements in same category, while loop runs only once because there was just 1 element at the beginning.