We build custom web applications
to grow your business.

How to create more than one random id for mysql query

I was recently working on a site constructed with php / mysql. I was generating data from a table with more than 80,000 rows. The mysql query was set up like this $result = mysql_query ("SELECT * FROM table WHERE content != '' AND id = RAND() LIMIT 5); The idea was to select 5 random rows from the table where content did not equal to zero. This worked, but was very taxing on web page speed, so i had to devise a way to increase speed by changing the way I queried the table. This is what I did: // Set a while loop to get 5 random numbers between 1 and 80,000. These 5 numbers will be our random id's $i = 1; while ($i <= 5) { srand ((double) microtime( )*1000000); $random_number = rand(0,80000); // Set $var to look and add "|| id = $var" at each loop $var = "id = '".$random_number."' || ".$var; $i++; } // trim white space on both sides of variable, just for caution $var = trim($var); // Remove the last unwanted "||" at the end of the variable $var = substr($var, 0, -2); echo $var; $result = mysql_query ("SELECT * FROM table WHERE content != '' AND ".$var."") The result will look like this $result = mysql_query ("SELECT * FROM table WHERE content != '' AND id = '44837' || id = '26086' || id = '7406' || id = '51184' || id = '33716' ") You now have a table showing 5 different products every time the viewer opens the page and the web page speed time - remarkable!