how to select items in while counter, in php

Asked

Viewed 150 times

1

I created an admin page where I register the book data in the database. I made this html where this data will be shown. the matrix will create this block "cabtitulo" with all the books registered on the administration pages, but I would like it to be visible only 4 of these blocks. so I put down 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 turn green, not the ones 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>';
}

?>
  • You are setting all the contents of <article> in green color.

2 answers

1


Everyone will turn green because class .livro shall be applied to all <article class="livro">. Besides while to write a CSS does not make sense. Maybe a if, but it’s still not best practice.

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

.livro{
    background-color:green;
}

And in the while put the check straight on the tag article which 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">
  • Thank you, you helped me so much!!

0

Try to do something like this:

Create the class that will define 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>
  • 1

    worked, thanks!!

    1. It is interesting that you mark one of the two answers as "solved"
    1. Your questions have a very close relationship with something I’ve been working on called the Traveler Books Platform. Are you interested in talking more about it? If so, you can contact me by email [email protected]. Success!

Browser other questions tagged

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