[Solved] How do i display images from MySQL database in a JavaScript image slider?


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 . "https://stackoverflow.com/" . $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="https://stackoverflow.com/questions/45704413/./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>

4

solved How do i display images from MySQL database in a JavaScript image slider?