简体   繁体   English

如何显示数据库中的随机图像?

[英]How do I display random images from my database?

I am currently creating a program which displays random images from a click event. 我目前正在创建一个程序,该程序显示来自click事件的随机图像。

I have code which should (but currently isnt) display random images from a folder of mine however, I have these images uploaded in my database instead (defined as large blobs). 我有应该(但目前不是)显示我的文件夹中的随机图像的代码,但是,我将这些图像上传到了数据库中(定义为大斑点)。 I would like to randomly output these images from my database instead (with the use of MySqli of course). 我想从我的数据库中随机输出这些图像(当然使用MySqli)。

How can I approach this? 我该如何处理?

My current code at the moment is : 目前,我当前的代码是:

JS: JS:

    var myImg = ["fruit1.jpg", "fruit2.jpg", "fruit3.jpg", "fruit4.jpg", "fruit5.jpg", "fruit6.jpg"];



//create a function named displayImage
//it should not have any values passed into it

var inputs = document.querySelectorAll('input');

for(var i = 0; i < inputs.length; i++) {
  inputs[i].addEventListener('click', function() {
    var num = Math.floor(Math.random() * 12);
    this.nextElementSibling.src = myImg[num];
  })
}

Example of the relevant html code: 相关html代码示例:

<div class="boxa">A1
    <input type=button value="Display Random Image">
    <img src="config.php" name="canvas" />
</div>

As many of us observed, you're currently using javascript to retrieve items/data from the database. 正如我们许多人观察到的那样,您当前正在使用javascript从数据库中检索项目/数据。 There are two ways for you to get the image in your database. 您可以通过两种方式在数据库中获取图像。 First is to get rid of your javascript and retrieve data using PHP, or use third-party js plugin like AJAX so you could still retrieve data using javascript. 首先是摆脱JavaScript并使用PHP检索数据,或者使用第三方js插件(如AJAX),以便仍可以使用javascript检索数据。 The difference is, AJAX doesn't reload the entire page. 不同之处在于,AJAX不会重新加载整个页面。 But since, you didn't tag AJAX in your question, we could do it in php. 但是,既然您没有在问题中标记AJAX,我们就可以在php中完成。

index.php index.php

<?php
  ... //Connection to database
  session_start();
  $_SESSION['ctr'] = ((isset($_SESSION['ctr'])) ? $_SESSION['ctr'] : 0);
  if(isset($_GET['incrementBtn']){
    $_SESSION['ctr']++;
  }
  $ctr = $_SESSION['ctr'];
  $imageArray = array();
  $result = $db->query("Select * from image"); //Retrieval Query
  for($x=0; $rows = mysqli_fetch_array($result); $x++){
    $imageArray[$x] = $rows['images']; //The Attribute name of your image, here i simply assume that it is 'image'
  }
?>
<div class="boxa">A1
    <form method="get" action="index.php">
        <input type="submit" name="incrementBtn" value="Display Random Image">
    </form>

    <img src="<?php echo $imageArray[$ctr]; ?>" name="canvas" />
</div>

Hope this helps. 希望这可以帮助。 Please correct me if something went wrong with this code, since I haven't tried this code because im using my mobile to answer this question. 如果此代码出了问题,请更正我,因为我没有尝试过此代码,因为我使用手机来回答此问题。 Thanks! 谢谢! :D :D

On the client side, there's no reason to make an AJAX call to figure out what image to show. 在客户端,没有理由进行AJAX调用以显示要显示的图像。 Your <img> tag can reference your PHP script directly: 您的<img>标记可以直接引用您的PHP脚本:

<img src="getRandomImage.php" />

Normally, you're using PHP to return HTML, but there's no reason it can't return binary data as well. 通常,您使用PHP返回HTML,但是没有理由也不能返回二进制数据。 Here, we're just letting the browser do the work of making the request. 在这里,我们只是让浏览器完成发出请求的工作。 Now, it's up to your server-side script to output the image. 现在,由服务器端脚本来输出图像。

In getRandomImage.php , first you'll need to query for a random image. getRandomImage.php ,首先需要查询随机图像。 Best to let the database engine do this, as there's no sense in shuffling excess data between your application and your database server. 最好让数据库引擎执行此操作,因为没有必要在应用程序和数据库服务器之间改组多余的数据。 Your query will look something like this: 您的查询将如下所示:

SELECT blobData FROM images ORDER BY RAND() LIMIT 1;

( blobData in this case is the name of the column containing the binary image data.) (在这种情况下, blobData是包含二进制图像数据的列的名称。)

Use your usual methods for making the query and getting the data. 使用常规方法进行查询和获取数据。 Now, to output it to something the browser can use, first we have to set the appropriate headers. 现在,要将其输出到浏览器可以使用的东西,首先我们必须设置适当的标头。 The first sets the response content type to be JPEG. 第一个将响应内容类型设置为JPEG。 (Change it to whatever is appropriate for you image type, if you're not outputting JPEG. (如果不输出JPEG,请将其更改为适合您的图像类型的任何内容。

header('Content-Type: image/jpeg');

Next, we need to prevent caching. 接下来,我们需要防止缓存。 This is important, as we're changing the response data for every request to this script: 这很重要,因为我们正在更改对此脚本的每个请求的响应数据:

header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

Now, just output your image data. 现在,仅输出图像数据。

echo $row['blobData'];

If all goes well, you should see the image in your image tag. 如果一切顺利,您应该在图像标签中看到该图像。

Improvements 改进措施

Normally when you make a GET request, all subsequent GET requests to the same URL with the same request data should return the same response. 通常,当您发出GET请求时,对具有相同请求数据的相同URL的所有后续GET请求应返回相同的响应。 While this isn't a technical requirement, it's a best practice that enables caches and what not to work correctly. 尽管这不是技术要求,但它是启用高速缓存以及无法正常运行的最佳实践。

It is possible for you to still have cacheable images, while making the selection random. 可能的,你仍然有缓存的图片,同时使选择随机的。 To do this, all you have to do is redirect to the image. 为此,您要做的就是重定向到该图像。 For example, getRandomImage.php might do something like this: 例如, getRandomImage.php可能会执行以下操作:

SELECT id FROM images ORDER BY RAND() LIMIT 1;

Then the response might just be a redirect: 然后,响应可能只是重定向:

header('Location: image.php?id=' . $row['id']);

Then in image.php , you'll load the image by ID (not randomly) and output it, just as we did in the first example. 然后,在image.php ,您image.php ID加载图像(不是随机地)并将其输出,就像在第一个示例中一样。 Ideally, your images would just be static files and be accessible without this subsequent database lookup, and that random selection script could redirect to a static file directly. 理想情况下,您的图像只是静态文件,无需后续数据库查找即可访问,并且随机选择脚本可以直接重定向到静态文件。 By default, PHP will do a 302 status code causing a non-permanent redirect which won't be cached in well-behaved clients. 默认情况下,PHP会执行302状态代码,导致非永久重定向,该重定向不会缓存在行为良好的客户端中。

You can use jQuery for a simple Ajax request: 您可以将jQuery用于简单的Ajax请求:

<div class="boxa">A1
  <input id="rndimgbtn" type=button value="Display Random Image">
  <img id="rndimg" src="config.php" name="canvas" />
</div>

$("#rndimgn").click(function(){
  $.ajax({
    url: "./path/to/getmyrandomimage.php", 
    success: function(result){
      var data = $.parseJSON(result);
      $("#rndimg").attr("src", "data:"+data.mime+";base64,"+data.image});
    }
  });
});

And for the PHP: 对于PHP:

#getmyrandomimage.php
$db = mysqli_connect("localhost","user","pass","autoselectdb");
$sql = "SELECT image, mime FROM table ORDER BY RANDOM() LIMIT 1";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);

die(json_encode((object)[
  "image" => chunk_split(base64_encode($result['image'])),
  "mime" => $result['mime']
]));

Remember to store your images as normal blobs, not encoding or anything. 请记住,将图像存储为普通Blob,而不是编码形式或其他任何形式。 You also need to store the image mime type, otherwise js don't know what image format its trying to render. 您还需要存储图像mime类型,否则js不知道其尝试呈现的图像格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在表格中显示随机图像 - How do I display random images to a table 如何让这个 javascript 以随机顺序显示图像? - How do I make this javascript display the images in random order? 如何在 React 中显示图像,这些图像作为文件下载并保存在服务器上的文件夹中,文件路径存储在我的数据库中? - How do I Display Images in React which are downloaded as Files & saved in a Folder on the Server with the Filepath stored in my Database? 如何使用javascript以随机顺序显示文件夹中的图像? - How can I display images from a folder in random order with javascript? 如何让我的机器人从一组图像中随机选择一个图像 - How do I make my bot pick a random image from a selection of images 如何显示从MySQL数据库获取的随机文本和图像? - How do I display a random text and image taken from a MySQL Database? 如何使用JavaScript显示来自parse.com数据库的图像? - How do I display images from parse.com database using javascript? 如何在 React Native 中显示 Firebase 存储中的所有图像而不需要图像名称? - How do I display all of the images from my Firebase Storage in React Native without needing image names? 如何从表中的数据库中弹出图像 - How to do popup images from my database inside a table 如何从文件夹中选取图像并以 HTML 格式显示? - How do I pick images from folder and display in HTML?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM