2

Hi Im trying to build a dynamic navigation menu similar on how wordpress does it or so I think but my problem is that my script retrieves only 1 value from my database. What I was trying to accomplish here is to fetch all menu data in my database and store them in a multidimensional array

My database structure looks like this:

enter image description here

Here is how I retrieve the data

global $db;
    $sql = "SELECT * FROM lm_menu";
    $res = $db->prepare($sql);
    $res->execute();
    $result = $res->fetchAll();
    foreach ($result as $opt_h):
              $nav = array(
        array(
            'id' => $opt_h['id'],
            'name' => $opt_h['name'],
            'link' => $opt_h['ref'],
            'parent' => $opt_h['parent']
        )
    );
    endforeach;

And this is the function that reads the array

    function GenerateMenu($nav)
{
    $html = '';
    $html = '<ul class="nav navbar-nav">';
    foreach($nav as $page)
    {
        $html .= '<li>';
        $html .= '<a href="' . $page['link'] . '">' . $page['name'] . '</a>';
        $html .= GenerateNavHTML($page['sub']);
        $html .= '</li>';
    }
    $html .='</ul>';
    return $html;
}

I tried looking for an answer from google but found no luck I saw an article from SO but I didn't tried it because on that article it uses a mysql_* functions while I use PDO functions. Please Help me guys on this one

1 Answer 1

4

The problem is every iteration, $nav = array( is overwritten.

Might as well just return $nav = $res->fetchAll(PDO::FETCH_ASSOC);. No need to loop and reassign.

Sign up to request clarification or add additional context in comments.

1 Comment

I see didn't think it could work that way.. thanks mate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.