You are here: Re: [PHP] random row « PHP « IT news, forums, messages
Re: [PHP] random row

Posted by Jasper Bryant-Greene on 11/16/05 06:19

John Taylor-Johnston wrote:
> My question is simnple. I want to randomly select a row in a mysql
> table. I have a primary id.
>
> <?php
> $server = "localhost";
> $user = "foo";
> $pass = "foo";
> $db="foo_db";
> $table="foo_table";
> $myconnection = mysql_connect($server,$user,$pass);
> mysql_select_db($db,$myconnection);
>
> $sql = ??;
>
> $news = mysql_query($sql) or die(print "<font
> color=red>".mysql_error()."</font>");
> while ($mydata = mysql_fetch_object($news))
> {
> ??
> }
> ?>
>

If your table isn't too big, it's fine to do:

SELECT * FROM mytable ORDER BY RAND() LIMIT 1

If you've got more than a few 10,000s of rows, you might want to look at
other ways, like selecting a random row based on the primary key by
generating a random number in PHP before executing the SQL.

Jasper

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация