John Davidson

php - Set first bootstrap card (item) as active


I'm using carousel to display data from database and I tried to set first card active but it won't work and cards are static. Cards works fine without php. I was trying to use boolean variable and set active class with some conditions but it didn't work.

      <div id="recipeCarousel" class="carousel slide w-100" data-ride="carousel">
<div class="carousel-inner w-100" role="listbox">
$query = "SELECT * FROM table_cards";
$result = mysqli_query($con, $query);

while($row = mysqli_fetch_assoc($result)) {
$image = 'uploads/'.$row['images'];
$isFirst = True;
if ($isFirst == True) {
$isFirst == False;
<div class="carousel-item active" data-interval="2000">
} else {
<div class="carousel-item" data-interval="2000">
<?php } ?>
<div class="col-md-4">
<div class="card">
<img class="card-img-top" src="<?php echo $image; ?>" alt="Card image cap">
<div class="card-body">
<h5 class="card-title"><?php echo $row['name']; ?></h5>
<p class="card-text text-left"><i class="fas fa-ruler-combined"></i> <strong>Size</strong>: <?php echo $row['size']; ?><br> <i class="fas fa-money-bill-wave"></i> <strong>Price</strong>: <?php echo $row['price']; ?><br><i class="fas fa-home"></i> <strong>House type</strong>: <?php echo $row['house_type']; ?><br><br><i class="fas fa-bed"></i> <?php echo $row['bed']; ?><i class="fas fa-toilet"></i> <?php echo $row['toilet']; ?></p>
<a href="gallery.html#first-post" class="stretched-link"></a>
<div class="card-footer">
<small class="text-muted">Lorem</small>
<?php } ?>
<a class="carousel-control-prev w-auto" href="#recipeCarousel" role="button" data-slide="prev">
<span class="carousel-control-prev-icon bg-dark border border-dark rounded-circle" aria-hidden="true"><i class="fas fa-angle-left fa-2x carousel-icon mr-1"></i></span>
<span class="sr-only">Previous</span>
<a class="carousel-control-next w-auto" href="#recipeCarousel" role="button" data-slide="next">
<span class="carousel-control-next-icon bg-dark border border-dark rounded-circle" aria-hidden="true"><i class="fas fa-angle-right fa-2x carousel-icon ml-1"></i></span>
<span class="sr-only">Next</span>

My Answer:
You can achieve this by adding a conditional statement in your PHP code to determine if the current card being generated is the first one, and if so, add the `active` class to it. Here's an example of how you can do this:


Rate this post

4 of 5 based on 9502 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us