本文介绍了如何在JavaScript图像滑块中显示MySQL数据库中的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码可以从数据库中获取所有图像.所有这些图像连续显示3,然后开始下一行.我想要一个图像滑块,该滑块可以从数据库中获取所有图像并显示它们.包括JavaScript代码在内的任何帮助都将非常有帮助,因为我并不是很擅长.谢谢!

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 images from the database and displays them. Any help including a JavaScript code would be very helpful as i'm not really good at it. thanks!

$sql = "SELECT FILE_NAME FROM images LIMIT 0,6";
    $result = mysqli_query($conn, $sql) or die("bad request: $sql");
        $i = 0;
    while($row = mysqli_fetch_assoc($result)) {
        if($i%3 == 0)
        {
            echo "<tr>";
        }
        echo"<td><img src='user_data/{$row['FILE_NAME']}' width=200 height=200></td>";
        if($i%3 == 2) {
            echo"</tr>";
        }
    }

推荐答案

这是一个非常基本的Slideshow-from-PHP应用程序.可以轻松地对其进行修改或构建.图像名称(file_name)从数据库中拉出,然后推入图像src值的JavaScript数组中.确保您还指定了图像目录(实际存储图像的位置)以匹配您自己的图像.幻灯片播放自动播放,其中包含一个简单的图像预加载器.

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>

这篇关于如何在JavaScript图像滑块中显示MySQL数据库中的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:04