Berikut adalah aplikasi Slideshow-from-PHP yang sangat mendasar. Itu dapat dengan mudah dimodifikasi atau dibangun. Nama gambar (file_name
) ditarik dari database, lalu dimasukkan ke dalam larik JavaScript dari nilai src gambar. Pastikan Anda juga menentukan direktori gambar (tempat gambar sebenarnya disimpan) agar sesuai dengan milik Anda. Prapemuat gambar sederhana disertakan, saat tayangan slide diputar secara otomatis.
<?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>