how to select items in while counter, in php

1

I have created an admin page where I have entered the data for books in the database. I made this html where this data will be shown. the array will create this block "header" with all the books registered in the admin pages, but I would like to have only 4 of those blocks visible. so I put the background-color: green function down there, to check if my code worked, if it worked, I would put a display leaving those other blocks invisible. but all the blocks are green, not bigger than 3, as I defined.

<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>';
}

?>
    
asked by anonymous 30.12.2017 / 23:38

2 answers

1

All will go green because the .livro class will be applied to all <article class="livro"> . In addition to this while to write a CSS does not make sense. Maybe a if , but still not the best practice.

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

.livro{
    background-color:green;
}

And in while put the direct check on the article tag that will add the class if the $contador is greater than or equal to 3:

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

The result would be the tag:

<article class="livro">
    
31.12.2017 / 00:27
0

Try to do something like this:

Create the class that will set the color:

.corContador { background-color: #0f0; }

Inside the loop, check the counter and assign the class:

<div class="<?php $contador < 3 ? 'corContador' : '' ?>">
    <!-- seus dados -->
</div>
    
31.12.2017 / 00:32