kendra Posted November 3, 2007 Share Posted November 3, 2007 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. Quote Link to comment https://forums.phpfreaks.com/topic/75873-solved-need-help-with-loop-and-random-number/ Share on other sites More sharing options...
Psycho Posted November 3, 2007 Share Posted November 3, 2007 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 Quote Link to comment https://forums.phpfreaks.com/topic/75873-solved-need-help-with-loop-and-random-number/#findComment-384016 Share on other sites More sharing options...
kendra Posted November 3, 2007 Author Share Posted November 3, 2007 Thank you so much. As I said I don't know what I'm doing. I had no idea it was so simple. Quote Link to comment https://forums.phpfreaks.com/topic/75873-solved-need-help-with-loop-and-random-number/#findComment-384395 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.