简体   繁体   中英

How can i fill up a bootstrap carousel with images from database?

Trying to fill up a bootstrap carousel with multiple images from database,this is my code yet but doesnt seem to work. Im using PHP PDO,so got a query fetched before what my foreach based on.The query is fine cause without the carousel it lists the images as should be.The issue lays within these lines.

<?php
$stmt = $pdo->prepare("SELECT * FROM images");
                   
                           $stmt->execute();
                           $image = $stmt->fetchAll();
?>

<?php foreach($image as $images) 
   {
?>
                     
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img class="d-block w-100" src="/upload/<?php echo $images['image']?>" alt="First slide">
    </div>
 
<div class="carousel-item">
<?php 
}

 ?> 
 </div> 



</div>
    </div>
  </div>
  
  <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="false"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="false"></span>
    <span class="sr-only">Next</span>
  </a>
  

Place <div class="carousel-inner"> outside the loop, you should only loop over

<div class="carousel-item active">
   <img class="d-block w-100" src="/upload/<?php echo $images['image']?>" alt="First slide">
</div>

Example:

<?php
$stmt = $pdo->prepare("SELECT image FROM images");
$stmt->execute();
$images = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">
    <?php foreach ($images as $index => $image): ?>
    <div class="carousel-item<?= !$index ? ' active' : '' ?>">
      <img class="d-block w-100" src="<?= $image['image'] ?>" alt/>
    </div>
    <?php endforeach; ?>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM