使用PHP显示数据库中的随机图像

时间:2018-02-02 02:08:13

标签: php sql

我希望显示随机选择的图像或我从数据库中选择的图像。

thumbnail {
float: left;
}
$query1=mysqli_query($db_con,"select * from image_tb");
   while($row=mysqli_fetch_array($query1)){
   $img = "<th><img src='".$row['image']."' width='260px';height='180px;' ></th>";
   $image_number = $row['id'];
   
   

<div class="block-content collapse in">
     <div class="row-fluid padd-bottom">
     <div class="span3">
//i want to display here the first image on my database but i don't know how to code it properly. 
      <a href="#" class="thumbnail">
      if (1 == $image_number){
          <?php echo "$img"; ?>
      }
       </a>
       </div>
       <div class="span3">
//the 2nd image from database
      <a href="#" class="thumbnail">
      if (2 == $image_number){
          <?php echo "$img"; ?>
      }
      </div>   
     </div>
<?php
  }
?>
     </div>
我真的不知道如何正确编码。

2 个答案:

答案 0 :(得分:0)

您可能想要编写另一个函数来获取随机图像, 您的查询应如下所示:

SELECT * FROM image_tb ORDER BY RAND() LIMIT 1;

在我看来,这似乎是从数据库中选择随机行的最有效方法。然后你可以用PHP做任何你想做的事。

但是你必须要运行两个查询。您可能会尝试使用union:

SELECT * FROM image_tb ORDER BY RAND() LIMIT 1 UNION SELECT * FROM image_tb ORDER BY id LIMIT 2;

将在两张第一张照片之后给你3行(第一次随机)

Haven未对此进行测试

答案 1 :(得分:0)

<?php
$query1=mysqli_query($db_con,"select id, image from image_tb");
while($row=mysqli_fetch_array($query1)){
   $images[$row['id']] = $row; //the $images array will store the images id from image_tb as an index, so you can call it directly like $images[x]
}
   $random_img = array_rand($image); // this will give you a random image
?>

<div class="block-content collapse in">
     <div class="row-fluid padd-bottom">
     <div class="span3">
    <!-- i want to display here the first image on my database but i don't know how to code it properly.-->
      <a href="#" class="thumbnail">
          <img src="<?php $images[$random_image] ?>" width="260px" height="180px">
       </a>
       </div>
       <div class="span3">
    <!-- the 2nd image from database -->
      <a href="#" class="thumbnail">
          <img src="<?php $images[$random_image] ?>" width="260px" height="180px">
      </a>
      </div>
     </div>
</div>
<?php