Jump to content

Archived

This topic is now archived and is closed to further replies.

feri_soft

random articles

Recommended Posts

Can someone explain me how it's done.For example u have a DB(mysql).And how to select and list lets say 5 random articles from it.Can you tell me please?? [img src=\"style_emoticons/[#EMO_DIR#]/smile.gif\" style=\"vertical-align:middle\" emoid=\":smile:\" border=\"0\" alt=\"smile.gif\" /]

Share this post


Link to post
Share on other sites
AFAIK, basically there is no built-in function in PHP or MySQL that allows you to do that. You'll have to use a workaround. A Google Search may be helpful.

Share this post


Link to post
Share on other sites
there is something like

select * from x order by rand() limit 5

but is that enought??

Share this post


Link to post
Share on other sites
Probably it works and it's effective if you have a few rows, but I think this could cause problems (use a lot of resources) if there are many rows.

Share this post


Link to post
Share on other sites
On a table containing 10,000+ records I got this level of performance, selecting and printing 5 random records

[code]$t1 = microtime(true);
$res = mysql_query("SELECT COUNT(*) FROM sales") or die(mysql_error());
echo '<pre>';
echo mysql_result($res, 0), ' records searched<br/>';

$res = mysql_query("SELECT * FROM sales ORDER BY RAND() LIMIT 5") or die(mysql_error());
while (list(,$code,$value) = mysql_fetch_row($res)) {
    printf ('%3s %8.2f<br/>', $code, $value);
}
$t2 = microtime(true);
$t = $t2-$t1;
printf ('Time taken %0.3f seconds', $t);
echo '</pre>';[/code]

Output -->

[code]10917 records searched
005    16.00
005     8.00
750    66.00
724     6.40
004   175.37
Time taken 0.018 seconds[/code]

Share this post


Link to post
Share on other sites
Barand, I found the article:

[a href=\"http://www.greggdev.com/web/articles.php?id=6\" target=\"_blank\"]http://www.greggdev.com/web/articles.php?id=6[/a]

[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]$random_row = mysql_fetch_row(mysql_query("select * from YOUR_TABLE order by rand() limit 1"));

$random_row will be an array containing the data extracted from the random row. However, when the table is large (over about 10,000 rows) this method of selecting a random row becomes increasingly slow with the size of the table and can create a great load on the server. I tested this on a table I was working that contained 2,394,968 rows. It took 717 seconds (12 minutes!) to return a random row.[/quote]

Share this post


Link to post
Share on other sites
I am not disagreeing, but their threshold of 10,000 is a little pessimistic.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.