Create a menu with categories

Asked

Viewed 138 times

0

I am developing a project in PHP and Mysql, and would like to create a menu that shows the categories registered in a database.

In this case I have two related tables whose names are tbl_categorias and tbl_subcategorias, which have the following fields:

tbl_categoria

categoria_id | categoria
----------------------------
1            | Aço e Metais

===================================

tbl_subcategoria

subcategoria_id | subcategoria | categoria_fk
-----------------------------------------------
1               | Ferro        | 1

How can I create a menu (categories) that also contains a submenu (subcategories) in PHP? At first I’m trying to create a PHP code to insert it into the HTML tags below:

<ul>

<li></li>

</ul>

How can I proceed?

1 answer

0


<ul>

<li></li>

</ul>

You want to create a menu and submenu with the categories and subcategories coming from the database, this way?

<?php
    // Conexão com o Banco (local)
    $host = "localhost";
    $user = "root";
    $pass = "";
    $conexao = mysqli_connect($host, $user, $pass) or die(mysqli_error());
    mysqli_select_db($conexao, "nome_do_banco") or die(mysqli_error());
    mysqli_set_charset($conexao, 'utf8');

    // Busca as categorias do banco
    $sql = "SELECT * FROM tbl_categoria";
    $query = mysqli_query($conexao, $sql);
    while ($row = mysqli_fetch_array($query)) {
        $categoria_id = $row['categoria_id'];
        $categoria = $row['categoria'];
        ?>
        <ul>
            <li><?php echo $categoria ?> 
                <ul>
                    <?php
                    // Ainda dentro do laço while que buscou as categorias, busca-se as subcategorias passando o id de referência "fk" 
                    $sql2 = "SELECT * FROM tbl_subcategoria WHERE categoria_fk = $categoria_id";
                    $query2 = mysqli_query($conexao, $sql2);
                    while ($row1 = mysqli_fetch_array($query2)) {
                        $subcategoria = $row1['subcategoria'];
                    }
                    echo "<li>$subcategoria</li>";
                    ?>                            
                </ul>
            </li>
        </ul>
        <?php
    }
    ?>

There must be another more "elegant" way to do this, but I believe this one should work.

  • Hi Julio. Thanks for the return. I will implement and adjust the above code as needed. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.