Jump to content

Recommended Posts

Hi all

 

I need to know how to randomise the below code so that it pulls one entry from the SQL at random every time the page is refreshed. Here's my code:

 

<?php
 $getleftads = mysql_query(" SELECT * FROM `left_advert_banners` ORDER BY id DESC");
 while ($showleftads = mysql_fetch_array($getleftads)) { ?>
      <a href="http://<?php echo $showleftads['url']; ?>" target="_blank">
      <img src ="images/banners/<?php echo $showleftads['image']; ?>" width="158" style="margin-bottom: 2px;" alt="<?php echo $showleftads['text']; ?>" title="<?php echo $showleftads['text']; ?>" />
      </a>
     <?php } ?>

 

Many thanks for your help

Pete

Link to comment
https://forums.phpfreaks.com/topic/236834-randomise-sql-query/
Share on other sites

I didn't test the following, but it should be something like this:

 

// FLOOR(1 + (RAND() * MAX(id)) is to randomly choose an 'id' from 1 (lowest) to MAX(id) (highest available)
$getleftads = "SELECT * FROM `left_advert_banners` WHERE `id` = (SELECT FLOOR( 1 + ( RAND( ) * MAX( `id` ) ) ) ) ORDER BY id DESC LIMIT 1

Link to comment
https://forums.phpfreaks.com/topic/236834-randomise-sql-query/#findComment-1217437
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.