Skip to content Skip to sidebar Skip to footer

How Do I Display Images From Mysql Database In A Javascript Image Slider?

I have following code which gets me all the images from the database. All these images are displayed 3 in a row and then next row starts. i want an image slider that takes all the

Solution 1:

Here is a very basic Slideshow-from-PHP application. It can easily be modified or built upon. Image names (file_name) are pulled from the database, then pushed into a JavaScript array of image src values. Make sure you also specify the images directory (where the images are actually stored) to match your own. A simple image preloader is included, as the slideshow autoplays.

<?php
$conn = new mysqli('localhost', 'root', 'password', 'images')
  or trigger_error('Connection failed.', E_USER_NOTICE);
}
$conn->set_charset('utf8');
$paths = [];
$dir = "./pics"; // images directory (change to suit)

$stmt = $conn->prepare("SELECT `file_name` FROM `images`");
$stmt->execute();
$stmt->bind_result($file);
while ($stmt->fetch()){
  $paths[] = $dir . "/" . $file;
}
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Slideshow from PHP</title>
</head>
<body>
<div>
  <!-- may set first image src in markup so initially visible -->
  <img id="slide" src="./pics/image1.jpg" alt="slideshow">
</div>
<script>
var time = 5000,    // time between images
    i = 0,              // index for changing images
    images = [],    // array of img src from PHP
    preloads = [],      // array of preloaded images
    slide = document.getElementById("slide");

images = <?php echo json_encode($paths); ?>; // from PHP to Js array
var len = images.length;

function changeImg(){
  slide.src = preloads[i].src;
  if (++i > len-1){
    i = 0;
  }
  setTimeout(changeImg, time);
}
function preload(){
  for (var c=0; c<len; c++){
    preloads[c] = new Image;
    preloads[c].src = images[c];
  }
}
window.addEventListener("load", function(){
  preload();
  setTimeout(changeImg, time);
});
</script>
</body>
</html>

Post a Comment for "How Do I Display Images From Mysql Database In A Javascript Image Slider?"