Jump to content

Randomise SQL query


petenaylor

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.