display products by listed category of the database with PHP PDO

Asked

Viewed 1,423 times

6

I’m having difficulty to list products by category, I created only one page and wanted to be dynamic the display of products according to the category listed in the database, but not certain and in PDO I don’t know how to do it. So I created a variable and passed the value by GET and yet it didn’t work, if anyone can help me thank!!

    <p class="titulo-produtos">Produtos..</p>

    <ul class="menu-produtos">
        <?php
            try {
                $categorias = $conexao_pdo->prepare("SELECT * FROM categorias ORDER BY nome ASC");
                $executa = $categorias->execute();

                if($executa){
                    while($reg = $categorias->fetch(PDO::FETCH_OBJ)){
                    /* Para recuperar um ARRAY utilize PDO::FETCH_ASSOC */
        ?>

        <li><a href="?categoria=<?php echo $reg->ID;?>"><?php echo $reg->nome?></a></li>

        <?php
                }//if
                    }//while
                else {
                    echo 'Erro ao listar as Categorias!!';
                }
            }//try
            catch(PDOException $e){
                echo $e->getMessage();
            }
        ?>
    </ul><!-- menu-produtos -->


    <ul class="produtos-internas">
        <?php
            $no = 'categoria';
            try {

                    $sql = "SELECT * FROM produtos WHERE categoria = ? AND status = 'on' ORDER BY nome ASC LIMIT 50";
                    if($produtos = $conexao_pdo->prepare($sql)){
                            if($produtos->execute(array($no))){
                                    while($reg = $produtos->fetch(PDO::FETCH_OBJ)){
                                            $dados[] = $reg;       
                                    }              
                            }              
                    }

            } catch(PDOException $e){
                    echo $e->getMessage();
            }

            if(isset($dados)){
                    foreach($dados as $object){
                            ?>
                            <li>
                                    <a href="#">
                                            <span class="rollover"></span>
                                            <img src="admin/uploads/<?php echo $object->foto; ?>" />
                                            <p>
                                                    <?php echo $object->nome ?><br /><br />

                                                    Por <span>R$ <?php echo $object->vlor_avista ?>,00</span> á vista<br />
                                                    ou 12x de R$ <?php echo $object->vlor_aprazo ?>,00 sem juros
                                            </p>
                                    </a>
                            </li>
                            <?php
                    }              
            }

            ?>
    </ul><!-- produtos -->

</section><!-- container -->

  • You either return as list of objects or already want to bring from the giving bank echo? And how is your table and which columns you will display of them?

  • i want to display with echo even are within a <li> the parameters that I want to display this part ta running so this listing all the registered products of the bank! i created an id and a name for category table and an id, name and category in products table, I wanted to display category 2 type displays products registered in category 2 and category 3 displays products registered with category 3 id understands...

  • 1

    Matthew, click [Edit] and add this information to the question.

  • What is this Ry dealing with? There is no catch in your code.

  • 1

    $no is a number or a text?

  • Well remembered @rray, I hadn’t even noticed. This variable $no is a category number that comes via GET?

  • yes I created a variable $no = $_GET['category'];

  • Error appears? $no is a number or string?

  • 1

    Try out these modifications here

  • appears: Notice: Undefined variable: no then I put the variable this error appears here: Notice: Undefined index: category

  • okk fixed the variable error like this: $no = 'category'; , but it is showing no error and no product heheh

  • Do the following, as a test create a link - print "<a href=\"{$_SERVER['PHP_SELF']}?categoria=1\">Primeira Categoria</a>"; - add it to that same page, click on it and see what returns.

  • is going back to the index page.php index.php? category=1

  • So change the value of $no manually see if you can get some feedback.

  • ok I’ll go trying kkk, obg for help!! :)

  • Then say what you’ve returned.

Show 11 more comments

1 answer

1

<p class="titulo-produtos">Produtos..</p>
<ul class="menu-produtos">
<?php
    try {
        $sqlCategoria = 'SELECT * FROM categorias ORDER BY nome ASC';
        $resCategoria = $conexao_pdo->prepare($sqlCategoria);
        $resCategoria->execute();
        $categorias = $resCategoria->fetchAll();

        if (count($categorias) === 0 ) { ?>
            echo '<li>Nenhuma categoria cadastrada.</li>';
        } else {
            foreach ($categorias as $categoria) {
                echo '<li><a href="?categoria=' . $categoria['ID'] . '">' .  $categoria['nome'] . '</a></li>';
            }
        }
    } catch(PDOException $e) {
        echo $e->getMessage();
    }
?>
</ul><!-- menu-produtos -->


<ul class="produtos-internas">
<?php
$categoriaId = null;
if (isset($_GET['categoria']) {
    $categoriaId = $_GET['categoria'];
}
try {
    if ($categoriaId === null) {
        $sql = 'SELECT * FROM produtos WHERE status = "on" ORDER BY nome ASC LIMIT 50';
        $resProdutos = $conexao_pdo->prepare($sql)
        $resProdutos->execute();
        $produtos = $resProdutos->fetchAll();
    } else {
        $sql = 'SELECT * FROM produtos WHERE categoria = ":categoriaId" AND status = "on" ORDER BY nome ASC LIMIT 50';
        $resProdutos = $conexao_pdo->prepare($sql)
        $resProdutos->execute(array($categoriaId));
        $produtos = $resProdutos->fetchAll();
    }

    if (count($categorias) === 0 ) { ?>
        echo '<li>Nenhuma categoria cadastrada.</li>';
    } else {
        foreach ($produtos as $produto) {
            echo '<li>';
            echo '<a href="#">';
            echo '<span class="rollover"></span>';
            echo '<img src="admin/uploads/' . $produto['foto'] . '" />';
            echo '<p>' . $produto['nome'] . '</p>;
            echo '</a>';
            echo '</li>';
        }
    }
} catch(PDOException $e){
    echo $e->getMessage();
}
?>
</ul><!-- produtos -->

Browser other questions tagged

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