Click to See Complete Forum and Search --> : Display Random Data


Dysan
04-29-2008, 07:16 AM
Hi, I have a database, containing people's names, ages, and gender's.
How do I randomly display a different persons record, upon refreshing the page?

deadfish
04-29-2008, 07:16 PM
I am going to take a guess at this as I am very new to PHP myself I can't promise it will work... but I guess it will be something like

To generate a random number between 0 and 100 do this:


srand((double)microtime()*1000000); <-use this to generate a random number
echo rand(0,100); <-change the 0, 100 to (1, the number of records)

to get the number of records you need something like this

$result = mysql_query("SELECT * FROM tablename") or die(mysql_error());
$count = mysql_num_rows($result) ;


.....

then you would need to query the random number...

SELECT * FROM `tablename` LIMIT 0 , 1 <replacing the 0 with your random number.

I hope that helps/works

skywalker2208
04-29-2008, 07:25 PM
I am going to take a guess at this as I am very new to PHP myself I can't promise it will work... but I guess it will be something like

To generate a random number between 0 and 100 do this:


srand((double)microtime()*1000000); <-use this to generate a random number
echo rand(0,100); <-change the 0, 100 to (1, the number of records)

to get the number of records you need something like this

$result = mysql_query("SELECT * FROM tablename") or die(mysql_error());
$count = mysql_num_rows($result) ;


.....

then you would need to query the random number...

SELECT * FROM `tablename` LIMIT 0 , 1 <replacing the 0 with your random number.

I hope that helps/works
That is how I would pretty much do except I would query the database for the number of results like you did with the mysql_num_rows. Then use the rand() and round() functions to randomly choose a number from your mysql_num_rows. Then round that number so you don't get a decimal. after that query the database with the limit like you showed in your example.

deadfish
04-29-2008, 09:27 PM
I'm so proud... i got it right :) haha I don't even know PHP...

NogDog
04-29-2008, 09:59 PM
You can simply do it in the query:

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

For more efficient SQL techniques, see http://phpbuilder.com/board/showthread.php?t=10338930.