问题描述:

I have a table photos with many photos in it and I need to select two at random:

In getnew.php

$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");

$result2 = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");

$row = $result->fetch_assoc();

$img1link = $row['link'];

// more stuff from $row

$row2 = $result2->fetch_assoc();

$img2link = $row2['link'];

// more stuff from $row2

However I need to prevent it from selecting the same photo twice (the selected photos must be different), i.e. $img1link should not = $img2link. I then need to retrieve the data using $.getJSON in another file, using an array at the end of getnew.php.

The array at the end of getnew.php:

echo json_encode(array('img1'=>$img1link,'img2'=>$img2link, ...(etc)... ));

How can I make sure the selected photos are different by the time the variable is stored in the array? I tried to create an if/else statement but didn't really understand what I was doing.

网友答案:

You can just execute once but get two instead so that you'll never pick the same row:

$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 2");
$row = $result->fetch_assoc();
$row2 = $result->fetch_assoc();
// invoke `->fetch` twice to get the first and second row
$img1link = $row['link'];
$img2link = $row2['link'];

Sidenote: Be careful of that ORDER BY rand() clause since it'll be slow on large data sets. You can use an alternative with @Bill Karwin's great answer

网友答案:

Run a single query -

 $result1 = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 2");

  while($row = $result->fetch_assoc()) {
      $imglink[] = $row['link'];
  }

You will get the links in $imglink[] array.

相关阅读:
Top