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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Randomly selecting a row in MySQL

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hello.

I am fairly new at PHP coding, and I'm trying really hard to make a script. There's something I don't know how to do yet.

How do I connect to MySQL and a database? In the table, how do I randomly choose a row, and then fetch the records in a variable format?

Thank you in advance.
 
Hi, heres a little light reading for you.


After this you'll need a good understanding of mysql functions to select a random record, but before you can select a random record you need to know how many records are in your database in the first place.

There are some very good step by step tutorials on and
which can teach you how to setup a database, connect using PHP and insert/update and read records from it.

This should be enough to get you started :) ______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
Thank you, KarveR.

There are 18 columns in my table, but the rows will vary. I just need to know how to get a random row, then get the record data for that row.
 
try this then: - you need a column called id that is a unique number.
SELECT @random:=truncate((rand() * your number of rows here),0), field1, field2 etc etc FROM your_table WHERE id = @random;

______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
Also if the number of rows is unknown, I tend to get the number of rows by this method:

$sql = mysql_query("SELECT * FROM $db_table WHERE 1");
$tabcnt = mysql_num_rows($sql);

Then follow KarveR's example, using the $tabcnt to get a random number.

'Does my thumb look big in this?'
homebut.gif
elshtroll
 
Mines not strictly correct, you need to add +1 to the calculation so that you can get the random to go to the highest record in the table too ...
@random:=truncate((rand() * your number of rows here + 1),0), ______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top