how to select items in while counter, in php



  • I created an administrator page where I register the book data in the database. I did this html where this data will be shown. the matrix will create this "cabtitulo" block with all books registered on the admin pages, but I would like it to be visible only 4 of these blocks. so I put it down there, the background-color:green function, to check if my code worked, if it worked, I would put a display leaving these other blocks invisible. but all the blocks become green, not the larger than 3, as I define.

    <div class="cabtitulo"><p>Promoções</p></div>
    <?php 
    $comando="select * from tb_promocao";
    $matriz=mysql_query($comando);
    $contador = 0;
    

    while ($contador<4) {
    while ($linha=mysql_fetch_array($matriz)) {
    ?>

    <article class="livro">
    <?php echo '<img src="img/' .$linha["imagempromo"]. '.jpg">'; ?>
    <p><span class="titulo"><?php echo $linha["titulopromo"]; ?></span><br>
    <span class="precode">R$ <?php echo $linha["precodelivro"]; ?></span><span class="preco">R$ <?php echo $linha["precoparalivro"]; ?></span><br><br></p>
    <button>adicionar<i class="fa fa-shopping-cart" aria-hidden="true"></i></button>
    <a href="">ver mais</a>
    <h2><?php echo $contador; ?></h2>
    </article>
    <?php
    $contador++;
    }//close matriz

    }//close contador

    while ($contador>=3) {
    echo '<style> .livro{ background-color:green;}</style>';
    }

    ?>



  • Everyone will be green because the class .livro will be applied to all <article class="livro">. Beyond that while to write a CSS makes no sense. Maybe a if, but still not the best practice.

    I would suggest instead of doing as you are doing, include in your CSS the class .livro:

    .livro{
        background-color:green;
    }
    

    And while put the direct check in the tag article which will add the class if the $contador be greater or equal to 3:

    <article<?php if($contador>=3){echo ' class="livro"';} ?>>
    

    The result would be the tag:

    <article class="livro">
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2