...

View Full Version : RAND() Function QUERY Help



winnard2008
08-05-2008, 10: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.



<?PHP


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 />";



}mysql_close($dbh);
?>




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.


cheers

Brandoe85
08-05-2008, 10:11 PM
Add it to the order by in your query:
SELECT * FROM table ORDER BY RAND() LIMIT 1;

Good luck;

winnard2008
08-06-2008, 10: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

derzok
08-06-2008, 02: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