View Full Version : RAND() Function QUERY Help

08-05-2008, 09:01 PM
Hi guys,

I have this bit of code which is just pulling an ID from the database and listing them on the page.

What I wanted to do was pull out one ID at random, but as I am new to PHP was wondering how I would do this.


mysql_select_db("$database", $dbh);

$result = mysql_query("SELECT * FROM portfolio ORDER BY id");

while($row = mysql_fetch_array($result))
echo $row['id'];
echo "<br />";


I tried the RAND() function but I don't think I coded it right.

Any help would be great, as the next part in my project is to pull out

info at random from database from 3 of the colmns in my table.


08-05-2008, 09:11 PM
Add it to the order by in your query:

Good luck;

08-06-2008, 09:33 AM
Hi Brandoe

Just after I posted I did a bit of research on W3schools and manged to create the random thing great.

Thanks for your input tho

08-06-2008, 01:36 PM
What is your application and how many rows do you expect to have? It makes me cringe when I see "ORDER BY RAND()" and a "LIMIT" in the same query. If you've got a lot of rows, mysql is going to generate a random number for each one of them - an expensive operation. Then it's got to go and find the lowest one of them - also expensive. I'm sure there are a number of threads in the mysql forum about this, but just in case have a read: http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum