Jump to content

[SOLVED] Need Help with Loop and Random Number


kendra

Recommended Posts

I am trying to create a script that will output a featured merchant from mysql database.  Here is what I have:

 

$result = mysql_query("SELECT max( id ) as id FROM `merchants`");

 

$row = mysql_fetch_array( $result );

     

$max = $row[id];

 

srand ((double) microtime( )*1000000);

 

$random_number = rand(2,$max);

 

$merchantid = mysql_query("SELECT * from merchants where $random_number=id");

 

$row = mysql_fetch_array( $merchantid );

 

for ( $featured=$random_number; $featured <> $row[id]; $random_number = rand (2,$max))

{

}

 

echo $row['merchant'];

 

Sometimes it works quickly and sometimes takes quite awhile.  I am very new to this, so am not sure the correct way.  I didn't want the maximum value to exceed the highest value I already have in the database (I thought this might make it quicker).  I also need the script to loop because I have several merchants that have been deleted through the years and not all id are consecutive.

 

Any help is appreciated.  Thanks.

Link to comment
Share on other sites

You have a loop that does nothing (no code between the brackets) what is the purpose? I'm not even sure of what you are trying to accomplish here. If you are just trying to pull a random entry from the database, use the RAND() function in MySQL.

 

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

 

This will select 1 random record from the table. Is this homework, because there is a page exactly explaining this with same code exactly as you have it.

 

http://www.mustap.com/databasezone_post_141_mysql-rand-function

Link to comment
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.