Dynamic image slider using Twitter Bootstrap & PHP with MySQL
I have received many requests from my readers to create image slider with admin where they can edit images and update text, so in this tutorial I am going to show you how to create image slider to get images, title and description from database and slide images. Using Twitter Bootstrap I have created a very simple and easy to understand slider and PHP & MySQL for dynamic option.
Tutorial Directory structure:
Database design and table:
database name => phpgang
table name => images
column names => id, title, desc, image, date
db.sql
Database file run in your MySQL to create database and add data in table.
-- -- Table structure for table `images` -- CREATE TABLE `images` ( `id` int(10) NOT NULL AUTO_INCREMENT, `title` text NOT NULL, `desc` text NOT NULL, `image` text NOT NULL, `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ; -- -- Dumping data for table `images` -- INSERT INTO `images` VALUES (1, 'HTML to PDF', 'How to Convert HTML to PDF in PHP with fpdf', '1.png', '2014-01-23 06:53:13'); INSERT INTO `images` VALUES (2, 'Bootstrap Contact Form', 'How to create Contact Form using Bootstrap', '2.png', '2014-01-23 06:53:13'); INSERT INTO `images` VALUES (3, 'Facebook Style Scroll Bar', 'How to create Facebook style scroll bar with jQuery and CSS.', '3.png', '2014-01-23 06:54:40'); INSERT INTO `images` VALUES (4, 'Instagram OAuth', 'How to login with Instagram OAuth using PHP', '4.png', '2014-01-23 06:54:40'); INSERT INTO `images` VALUES (5, 'PDO database connection in PHP', 'How to use PDO database connection in PHP', '5.png', '2014-01-23 06:56:49'); INSERT INTO `images` VALUES (6, 'Tweet on Twitter', 'How to post tweet on Twitter with PHP', '6.png', '2014-01-23 06:56:49');
db.php
Database configuration file edit database name, user and password as per your configuration.
<?php $connection = mysqli_connect('localhost','phpgang_usr','******','phpgang') or die(mysqli_error($connection)); ?>
Use Bootstrap libraries and define carousel classes.
<link rel="stylesheet" href="css/bootstrap.min.css" /> <script type="text/javascript" src="js/jquery-1.8.0.min.js"></script> <script src="js/bootstrap.min.js"></script>
Indicators
<ol class="carousel-indicators"> <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li> <li data-target="#carousel-example-generic" data-slide-to="1"></li> </ol>
carousel-indicators this class show slide indicator small circles here we show for 2 slides and make sure you define active slide you can select any slide to be active.
Show images slides with titles and description.
Slider content
<div class="carousel-inner"> <div class="item active"> <img src="images/img1.png" alt="Image 1"> <div class="carousel-caption"> <h3>Image 1</h3> <p>Description 1.</p> </div> </div> <div class="item"> <img src="images/img2.png" alt="Image 2"> <div class="carousel-caption"> <h3>Image 2</h3> <p>Description 2.</p> </div> </div> </div>
Here is item used for slide container carousel-caption used for Title and Description.
Finally we have Controls for navigation for next or previous.
Controls
<a class="left carousel-control" href="#carousel-example-generic" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> </a> <a class="right carousel-control" href="#carousel-example-generic" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> </a>
Above HTML is used to add Controls to go through next or previous.
PHP Code for Dynamic slider:
I have used ( How to Upload Image using jQuery with progress in PHP ) to upload images and add title and description.
1 Extra file added in image processing and make few changes in process upload file.
processupload.php
<?php ini_set("display_errors",1); if(isset($_POST)) { $Destination = 'images'; if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name'])) { die('Something went wrong with Upload!'); } $allowedExts = array("jpg", "jpeg", "gif", "png"); $RandomNum = rand(0, 9999999999); $ImageName = str_replace(' ','-',strtolower($_FILES['ImageFile']['name'])); $ImageType = $_FILES['ImageFile']['type']; //"image/png", image/jpeg etc. $ImageExt = substr($ImageName, strrpos($ImageName, '.')); $ImageExt = str_replace('.','',$ImageExt); if(!in_array($ImageExt, $allowedExts)) { die('Invalid file format only <b>"jpg", "jpeg", "gif", "png"</b> allowed.'); } $ImageName = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName); //Create new image name (with random number added). $NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt; move_uploaded_file($_FILES['ImageFile']['tmp_name'], "$Destination/$NewImageName"); echo '<form method="post" action="addimage.php"> <table width="100%" border="0" cellpadding="4" cellspacing="0"> <tr> <td align="center"><img src="images/'.$NewImageName.'"><input type="hidden" value="'.$NewImageName.'" name="image" /></td> </tr> <tr> <td align="center">Title:<br><input type="text" name="title" /></td> </tr> <tr> <td align="center">Description:<br><textarea name="desc"></textarea></td> </tr> <tr> <td align="center"><input type="submit" name="submit" value="Save" /></td> </tr> </table></form>'; } ?>
After upload it shows you title and description boxes and submit that to addimage.php file to add in database.
addimage.php
<?php include_once('db.php'); $image = mysqli_real_escape_string($connection,$_POST['image']); $title = mysqli_real_escape_string($connection,$_POST['title']); $desc = mysqli_real_escape_string($connection,$_POST['desc']); $query = "INSERT INTO `images`(`title`,`desc`,`image`) VALUES ('".$title."', '".$desc."', '".$image."')"; mysqli_query($connection,$query); header("location: index.php"); ?>
This file used to add data in database table images and redirect to slider page.
Image slider main file which is used to show slides.
index.php
Contains PHP code which get last inserted 6 images from database with title and description and arrange them in carousel slider settings and show you slider.
<?php include_once('db.php'); $query = "select * from images order by id desc limit 6"; $res = mysqli_query($connection,$query); $count = mysqli_num_rows($res); $slides=''; $Indicators=''; $counter=0; while($row=mysqli_fetch_array($res)) { $title = $row['title']; $desc = $row['desc']; $image = $row['image']; if($counter == 0) { $Indicators .='<li data-target="#carousel-example-generic" data-slide-to="'.$counter.'" class="active"></li>'; $slides .= '<div class="item active"> <img src="images/'.$image.'" alt="'.$title.'" /> <div class="carousel-caption"> <h3>'.$title.'</h3> <p>'.$desc.'.</p> </div> </div>'; } else { $Indicators .='<li data-target="#carousel-example-generic" data-slide-to="'.$counter.'"></li>'; $slides .= '<div class="item"> <img src="images/'.$image.'" alt="'.$title.'" /> <div class="carousel-caption"> <h3>'.$title.'</h3> <p>'.$desc.'.</p> </div> </div>'; } $counter++; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Dynamic image slider using twitter bootstrap & PHP with MySQL | PGPGang.com</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <style type="text/css"> img {border-width: 0} * {font-family:'Lucida Grande', sans-serif;} </style> </head> <body> <h2>Dynamic image slider using twitter bootstrap & PHP with MySQL Example. => <a href="https://www.phpgang.com/">Home</a> | <a href="http://demo.phpgang.com/">More Demos</a></h2> <link rel="stylesheet" href="css/bootstrap.min.css" /> <script type="text/javascript" src="js/jquery-1.8.0.min.js"></script> <script src="js/bootstrap.min.js"></script> <style> .carousel-caption { background-image: url("https://www.phpgang.com/wp-content/themes/PHPGang_v2/img/bg_sidebar.png"); } .carousel-inner>.item>img, .carousel-inner>.item>a>img { height:400px; width:700px; } </style> <div class="container" style="width: 730px;"> <h2>Dynamic Image Slider</h2><span style="float: right;margin-top: -30px;"><a href="addnew.php">Add More Images</a></span> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <?php echo $Indicators; ?> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> <?php echo $slides; ?> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> </a> <a class="right carousel-control" href="#carousel-example-generic" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> </a> </div> </div> </body> </html>
That’s all
You can easily update images and show them in slider helpful for beginner web developers and web designers.
Hope you like this tutorial please must submit your feedback in comments.
Tutorial Categories:
i have Confusion Plz let me know what mean of Boostrap ( or what is Boostrap)
It is an html, css, javascript framework that you can use as basis for creating a web sites or web applications.
Then Please also post some basic tutorial of BoosTrap so i can learn.
I cant find the image slider responsive. can any one suggest me
Hey I just want to take time and say tank you for this greats tutorial.. its great thing and I been looking for something like this for a very long time. Ones again Thank you and keep up good work.
I’ve tried to download code but it said “no email subscribe” whereas I’ve been subscribed. Could you please tell me how to download the code? thx
thank u sooooooooooooo much….after striving so much ur code worked for me perfectly
Please Tell me the html.inc file meaning and using purpose.
verryyyyyy verryy irritating site i am unable to download the slider code after Subscribe the email
Nip
Bitte sagen Sie mir die Datei html.inc Sinn und Zweck verwenden.
Ok, this is great tutorial. But i want to know how do you target in index.php with a href!
I want to see every picture individually on the individuall page. Lets say i have display.php and on that page i want to show picture from the slider and some text, how do i wrap link around that line so that it can take me on that page straight to display.php?
nice t1 guns noob
Hi.
Help me with this error please.
In the link to add new image i have the problem
You can remove that file its used for demo footer and header.
You can remove that file its used for demo footer and header.
yes u r right… i also have this warning as “html.inc” file is missing from the directory,, plz help??
i have error like this.
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:xampphtdocsdinamicsliderindex.php on line 6
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:xampphtdocsdinamicsliderindex.php on line 11
I have edited the db file and the error still occurs. please help me.. i want to learn about this.
or can you upload the sql file?
thanks.
i want to rotate through a group of items. For example display four images in one slider at a time and in the second slide again four images.(images fetch from database)
what is the “include(“../html.inc”);” in addnew.php page.give me answer
after solving that footer problem..now i dont have option to upload a new imge..it shows a blank page..what should i do???
i have also getting same error.
plzz,help.
i have solve the error. you have to put all the elements from form to closing form out of php block.
……
i have solve the error. you have to put all the elements from form to closing form out of php block.
……
i have got a notice of failed to open such stream of file –include(“../html.inc”); plz help??
hi can anyone tell how to limit image per in a lide
hi can anyone tell how to limit image per in a lide
hi can anyone tell how to limit image in a slide
hi can anyone tell how to limit image in a slide
Hello can anyone helpme, when I run the Demo and I try to upload an image the page addnew.php display the following error. what is this line : include(“../html.inc”); ? shoul I remove it or what must I do ?.
Remov that no need to use that file.
whats html.inc?
Thanx Everything Was perfect in that
I also want to know if we want to make only text slider ?
Anybody can help me out
You can remove pictures and use only text to make text slider.
Hi, how to set time to transictions? thanks
You can set time of transactions by changing css
find in the bootstrap.min.css file:
.carousel-inner > .item {
position: relative;
display: none;
-webkit-transition: 0.6s ease-in-out left;
-moz-transition: 0.6s ease-in-out left;
-o-transition: 0.6s ease-in-out left;
transition: 0.6s ease-in-out left;
}
and change 0.6s to the time you want. You also might want to edit time in the function call below:
.emulateTransitionEnd(2000)
at bootstrap.min.js in function Carousel.prototype.slide. That synchronize transition and prevent slide to disapear before transition ends.
Reference: http://stackoverflow.com/questions/17332431/how-can-i-control-the-speed-that-bootstrap-carousel-slides-in-items
thanks.
to solve the error in “include(“../html.inc”)” – you just need to erase the PHP tag then make like the following below
//put all the codes here with no PHP tag
Is it possible to display mutliple items by slide instead of just one?
THANKS
sir plz make toturial on how to make dynamic report in php.i want to make a dmc in php from mysql
hi sir, what is the addnew.php ? I didn’t seem to find a code under that filename on here so I’m confuse.
thanks for the share Sir…and i have a question: what if the image is more than one in each item?, would you show me the script for that? Please…
hi huzoor baksh .. aslm very nicely compiled dynamic query thnks for your effort i am stuck with 1 thing though.. i am getting the slider working ..
below each slider i would liketo have a btn – more -btn button this button should be a href to a page where all the data related to that particular slider id can be fetched from database via $_get method on the next page .. i am stuck howto echo current slider row id in this more button
i tried to get row [‘id ‘ as title and passed it down without any luck it just gives me single id — this id does not change with the next slider .. your help will be very much appreaciated thaks in advance ]
Hello, I would like to download your source for this slide but i cant subscribe with my e-mail. Your system doesnt work. Its possible to display more than one slide ?
thanks for this code