Using array instead of lots of db queries in PHP

Posted by Tural Teyyuboglu on Stack Overflow See other posts from Stack Overflow or by Tural Teyyuboglu
Published on 2011-11-21T20:32:02Z Indexed on 2011/11/22 1:51 UTC
Read the original article Hit count: 204

Filed under:
|
|
|
|

My function looks like that. It works but does lots of work (recursively calls itself and does lots of db queries.). There must be another way to do same thing but with array (with one query). I can't figure out how to modify this function to get it work with array. Please help.

function genMenu($parent, $level, $menu, $utype) {
    global $db;
    $stmt=$db->prepare("select id, name FROM navigation WHERE parent = ? AND menu=? AND user_type=?") or die($db->error);
    $stmt->bind_param("iii", $parent, $menu, $utype) or die($stmt->error);
    $stmt->execute() or die($stmt->error);

    $stmt->store_result();
    /* bind variables to prepared statement */
$stmt->bind_result($id, $name) or die($stmt->error);
    if ($level > 0 && $stmt->num_rows > 0) {
        echo "\n<ul>\n";
    }
    while ($stmt->fetch()) {
        echo "<li>";
        echo '<a href="?page=' . $id . '">' . $name . '</a>';
        //display this level's children
        genMenu($id, $level+1, $menu, $utype);
        echo "</li>\n\n";
    }
    if ($level > 0 && $stmt->num_rows > 0) {
        echo "</ul>\n";
    }
    $stmt->close();
}

© Stack Overflow or respective owner

Related posts about php

Related posts about mysql