Leon Rio
Leon Rio

Reputation: 83

PHP How to add active class to dynamic menu?

how can i add active class to dynamic menu.I use while for my product list.But i cannot understand how can i add to active class.

<div class="col-md-4">
        <h3>Products</h3>
        <div class="list-group">


         <?php
         $db = new connection(); 
         $productsor = mysqli_query($db,"select * from products");

         while($productcek = mysqli_fetch_assoc($productsor)){ ?>

         <a href="products.php?products_id=<?php echo $productcek['products_id'];?>" class="list-group-item"> <?php echo $productcek['products_ad']; ?> </a>
         <?php
       }
       ?>
     </div>
   </div>

Upvotes: 1

Views: 463

Answers (1)

Dale
Dale

Reputation: 10479

You need to check against a previously set _GET parameter and compare it in your while loop

while($productcek = mysqli_fetch_assoc($productsor)){ ?>

    <?php $active = (isset($_GET['products_id']) && $productcek['products_id'] == $_GET['products_id']) ? 'active' : null; ?>

    <a href="products.php?products_id=<?php echo $productcek['products_id'];?>" class="list-group-item <?= $active; ?>"> <?php echo $productcek['products_ad']; ?> </a>

<?php
}
?>

Upvotes: 1

Related Questions