Bootstrap Carousel Making Dynamic with PHP
Have you ever seen the news website display update news image slider ?. In this tutorial, we create dynamic image slider using bootstrap carousel where the image will be fetched from database and it displays also title and substring that fetched also from database. Each admin update news contain : image, title, content.. the bootstrap carousel update automatically by fetching image, title and substring of content from database MySQL.
This is ouput of dynamic carousel which we will create as shown by figure.1 below
The steps in creating dynamic Bootstrap Carousel
Look at the snippet code of index.php which limits the appearance of news displayed:
This is ouput of dynamic carousel which we will create as shown by figure.1 below
Fig.1 |
The steps in creating dynamic Bootstrap Carousel
1. Create database "db_carousel"In this step, we create database db_carousel.sql which contain source code as follow :
CREATE TABLE `berita` ( `id` int(10) NOT NULL AUTO_INCREMENT, `tanggal` date NOT NULL, `gambar` varchar(50) NOT NULL, `judul` varchar(200) NOT NULL, `konten` text NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latinAfter database created, fill each attribute and create folder img to store the image file.
2. Create file "koneksi.php"In order to make connection to database, we have create file koneksi.php as follow:
<?php $con=mysqli_connect("localhost","root","","db_carousel"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } ?>
3. Create file "index.php"Next step we create file index.php as interface to display dynamic slider.
Look at the snippet code of index.php which limits the appearance of news displayed:
<?php include "config/koneksi.php"; $query = "select * from berita order by id desc limit 3"; $res = mysqli_query($con,$query); $count = mysqli_num_rows($res); $slides =''; $Indicators =''; $counter =0; echo "<li data-target='#myCarousel' data-slide-to='0'></li>"; echo "<li data-target='#myCarousel' data-slide-to='1'></li>"; echo "<li data-target='#myCarousel' data-slide-to='2'></li>"; ?>Script above permit only three news displayed. If you want to add more, modfiy in code
$query = "select * from berita order by id desc limit 3";And do not forget you change also in the code :
echo "<li data-target='#myCarousel' data-slide-to='0'></li>"; echo "<li data-target='#myCarousel' data-slide-to='1'></li>"; echo "<li data-target='#myCarousel' data-slide-to='2'></li>";