Page 1 of 1

Randow choose a username in mysql

Posted: Wed Oct 19, 2011 10:25 pm
by aikoman
HI, i'm new here< i was looking for a forum about php and the first i found is you guys.

I got a question. I want to make a database where people can register with full name and email. and I wanted to know how to make a script that i can use like a raffle so that people that register can win prices. so I need a php script that when i click (choose a winner) it randomly choose a name from my database so they can win a price.

can anyone of you guys help me with this??

I'm a beginner in php.

thanks
AIKOMAN

Re: Randow choose a username in mysql

Posted: Wed Oct 19, 2011 10:42 pm
by Benjamin

Code: Select all

<?php
# @see http://www.greggdev.com/web/articles.php?id=6
# @foundOn google.com/search?q=choosing+random+mysql+row&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a
  //CODE FROM http://WWW.GREGGDEV.COM

  function random_row($table, $column) {
      $max_sql = "SELECT max(" . $column . ") 
                  AS max_id
                  FROM " . $table;
      $max_row = mysql_fetch_array(mysql_query($max_sql));
      $random_number = mt_rand(1, $max_row['max_id']);
      $random_sql = "SELECT * FROM " . $table . "
                     WHERE " . $column . " >= " . $random_number . " 
                     ORDER BY " . $column . " ASC
                     LIMIT 1";
      $random_row = mysql_fetch_row(mysql_query($random_sql));
      if (!is_array($random_row)) {
          $random_sql = "SELECT * FROM " . $table . "
                         WHERE " . $column . " < " . $random_number . " 
                         ORDER BY " . $column . " DESC
                         LIMIT 1";
          $random_row = mysql_fetch_row(mysql_query($random_sql));
      }
      return $random_row;
  }
  
  //USAGE
  echo '<pre>';
  print_r(random_row('YOUR_TABLE', 'YOUR_COLUMN'));
  echo '</pre>';
?>

Re: Randow choose a username in mysql

Posted: Wed Oct 19, 2011 10:44 pm
by twinedev

Code: Select all

SELECT `name`,`email` FROM `users` WHERE `status`='active' ORDER BY RAND() LIMIT 1
The key thing is the your are ordering by a random number, and limiting to just the first result.

Add other things to WHERE as needed

-Greg

Re: Randow choose a username in mysql

Posted: Tue Oct 25, 2011 5:22 pm
by aikoman
Thanks you guys very much.!!

Re: Randow choose a username in mysql

Posted: Tue Oct 25, 2011 5:29 pm
by egg82
man, you guys are fast O.o

Always happy to help!

Update: Just looked at the dates :lol: