how to select random data from table?

Codes here !

Moderators: macek, egami, gesf

jumpsalty
New php-forum User
New php-forum User
Posts: 3
Joined: Wed Nov 20, 2002 11:31 pm

how to select random data from table?

Postby jumpsalty » Wed Nov 20, 2002 11:36 pm

how do i select random data from a table?

User avatar
Joan Garnet
Moderator
Moderator
Posts: 387
Joined: Sat Aug 03, 2002 2:56 am
Location: Mars
Contact:

Postby Joan Garnet » Thu Nov 21, 2002 4:53 am

You can use the rand function combined with a query:

Code: Select all

<?php
$sql="select my_column from my_table'";
$result=mysql_query($sql,$db);
while ($row=mysql_fetch_array($result)){
      $total_num_rows = mysql_num_rows ( $result );
      $rand = ( rand ( 0, $total_num_rows ) );
      $random_data = $row [$rand];
      echo $random_data;
}
?>


:)

User avatar
Oleg Butuzov
Last Samuray
Last Samuray
Posts: 831
Joined: Sun Jun 02, 2002 3:09 am

Postby Oleg Butuzov » Sat Nov 23, 2002 10:10 am

selecrt * from sometable order by rand() limit 1

jumpsalty
New php-forum User
New php-forum User
Posts: 3
Joined: Wed Nov 20, 2002 11:31 pm

i dont think its efficient

Postby jumpsalty » Wed Dec 11, 2002 10:14 pm

the method that you use return all data and then we choose randomly from the data returned. problem if there is large data in the table

User avatar
Oleg Butuzov
Last Samuray
Last Samuray
Posts: 831
Joined: Sun Jun 02, 2002 3:09 am

Postby Oleg Butuzov » Thu Dec 12, 2002 12:39 am

$n=10; //num of recordes

selecrt `yourrows` from sometable order by rand() limit $n

or use a few querys =)


Return to “mySQL & php coding”

Who is online

Users browsing this forum: Majestic-12 [Bot], Yahoo [Bot] and 1 guest