开发者

To fetch Random/different records each time

I have 3 thumbnails which i want to rotate each time a user refresh the page. Therefore want to show different thumbnail each time. I have image name stored in the database. I am using this SQL query to fetch "select thumbnail from tablename order by rand() limit 1". It is fetching one thumbnail perfectly.

The problem is that sometime same images comes up. For example first time i refresh the page thumbnail 1.jpg shows but second time again 1.jpg comes up.

So what i am looking for is to have different thumbnail each time i 开发者_JAVA技巧refresh the page.

Can anyone provide me some suggestions to achieve this ?


this is not possible with random selection, as the same image can come again.

For the effect you want you need to use a cookie to store the last displayed image name and NOT display that image for the next request.

As you have confirmed in your comment you do not want to display the last displayed thumbnail. IN that case you can do this like this using sessions:

// get last shown from session if any
$last_shown = '';
if(isset($_SESSION['last_shown_thumb']))
    $last_shown = $_SESSION['last_shown_thumb'];

// select a thumbnail randomly which is not the one last shown
$query = "SELECT thumbnail FROM tablename WHERE thumbnail <> '" . $last_shown . "' order by rand() limit 1";
$res = mysql_query($query);
$row = mysql_fetch_row($res);
$curr_thumb = $row[0];

// set the current to last shown in session
$_SESSION['last_shown_thumb'] = $curr_thumb;


Assuming you are using PHP, you store the previous thumbnail in $current_thumbnail.
Then, you can do it like this

SELECT thumbnail FROM tablename WHERE thumbnail <> '$current_thumbnail' ORDER BY rand() LIMIT 1

Your query just needs to know what thumbnail you are currently displaying so you can filter it out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜