Search code examples
phpmysqlbootstrap-4carousel

Images loaded into a bootstrap 4 carousel from mysql database


I use a standard carousel of Bootstrap 4 framework. I want to use images from the mysql database. Problem is that a slideshow doesn't work. It shows images as a static ones one above the other instead of slides. Here is a link to a website: www.todays.com.pl/index-off.php .

Here is a carousel code:

<div id="demo" class="carousel slide" data-ride="carousel">
    <!-- Indicators -->
    <ul class="carousel-indicators">
        <li data-target="#demo" data-slide-to="0" class="active"></li>
        <li data-target="#demo" data-slide-to="1"></li>
        <li data-target="#demo" data-slide-to="2"></li>  
    </ul>

    <!-- The slides -->               
    <div class="carousel-inner">

    <?php while ($row = mysql_fetch_array($result3)) {      
        $id =($row['id']);                      
        $image =($row['image']);
    ?>

    <?php echo('<div class="carousel-item bnw-filter active">'); ?>
        <?php 
            echo '<a href="artykul.php?id='.$id.'">'; 
            echo '<img src="uplimg/'.$image.'" class="img-fluid">';
            echo '</a>'; 
        ?>
    <?php echo('</div>'); ?>    

    <? } ?>               
    </div>

    <!-- Left and right controls -->
    <a class="carousel-control-prev" href="#demo" data-slide="prev">
    <span class="carousel-control-prev-icon"></span>
    </a>
    <a class="carousel-control-next" href="#demo" data-slide="next">
    <span class="carousel-control-next-icon"></span>
    </a>
</div>

I think that problem may be here in this line:

<?php echo('<div class="carousel-item bnw-filter active">'); ?>

Originally there is a class "active" just for a first slide. All the other ones has no this class. So I don't have a clue how to assign this class just for a first slide/image if I make it dynamicly using images from database.

I am sure that someone experienced this problem before. Please help.


Solution

  • You are correct in assuming that the following line is incorrect:

    <?php echo('<div class="carousel-item bnw-filter active">'); ?>
    

    You only need one item that has class 'active'. To achieve this lets just check to see if we've already appended an active item to the DOM as such:

    <?php 
        $hasAddedActive = false;
        while ($row = mysql_fetch_array($result3)) {      
        $id =($row['id']);                      
        $image =($row['image']);
    ?>
    
    <?php 
        $divClass = 'carousel-item bnw-filter';
        $divClass .= $hasAddedActive ? '' : ' active';
        $hasAddedActive = true;
        echo('<div class="'.$divClass.'">'); 
    ?>
        <?php 
            echo '<a href="artykul.php?id='.$id.'">'; 
            echo '<img src="uplimg/'.$image.'" class="img-fluid">';
            echo '</a>'; 
        ?>
    <?php echo('</div>'); ?>    
    
    <? } ?>