Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

MYSQL random row 1

Status
Not open for further replies.

peacecodotnet

Programmer
May 17, 2004
123
US
I am using php to read from a table in a mysql database. I need to be able to run a select statement that selects * where field1='value1' and field2='value2'

I know how to do that, but then I need to select a random row from those results. How do I do that?

Any help would be greatfully appreciated.

Peace out,
Peace Co.
 
I have an example for you.

Natural join, with random, 30 rows
Code:
sql = 'SELECT cat_id, cat_title, word_id, word_word'
        . ' FROM `hangman_cat` , `hangman_words` '
        . ' WHERE word_cat_id = cat_id'
        . ' ORDER BY RAND( ) LIMIT 0, 30';

If you want only one result:
Code:
SELECT <field(s)> FROM <table(s)> WHERE <clause(s)> AND <clause(s)> ORDER BY RAND( ) LIMIT 0, 1
 
no problem :)
it's very cool for "random pics", "random quotes", etc.
I see a lot of people do a random function in php, but it's always best to do it in the sql database, if you can.
 
Just out of curiousity, is there a random function built into PHP (like Math.random() in Javascript or Java)?

--Chessbot

"So it goes."
Kurt Vonnegut, Slaughterhouse Five
 
Here, made for you! (now)
Code:
echo genRandom();

function genRandom($from = 1, $to = 10)
  {
    return rand($from, $to);
  }
 
so rand($a,$b) generates a random number?

makes sense...
Thanks.

--Chessbot

"So it goes."
Kurt Vonnegut, Slaughterhouse Five
 
rand needs a start and a stop.. $a, $b or whatever you might want to call it.

If called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and RAND_MAX. If you want a random number between 5 and 15 (inclusive), for example, use rand (5, 15).

reference:
 
that is much better than Math.random()!

--Chessbot

"So it goes."
Kurt Vonnegut, Slaughterhouse Five
 
yeah.. I think php is quite easy.. atleast when you know what you need to do :p

or wait, so is life.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top