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

Random Text

Status
Not open for further replies.

maxnamara

Programmer
May 1, 2001
4
ID
Could someone please give an example for select data randomly from MySQL dan PHP. The test changes randomly every 24 hours/ every 7 o'clock in the morning.

Any help would be appreciated.

Maxnamara
 
Sure. If I understand your question correctly, you want something like this:


[tt]

<?php

// connect to the database
$query = &quot;SELECT * FROM table&quot;;
$result = mysql(&quot;database&quot;,$query);
$rows = mysql_num_rows($result); // find the number of rows
$rand = rand(0,$rows); // will generate a random number from 0 to the number of rows in your database
$query = &quot;SELECT * FROM tablename WHERE id = $rand&quot;; // assuming your auto-increment field is id. rename it to what you want in the code.
$result = mysql(&quot;database&quot;,$query);
$data = mysql_result($result,0,&quot;field_that_you_want_to_get_data_from&quot;);

print $data;

?>


[/tt]

That should do it. It selects a random row from your database and prints it to the screen.

Hope this helps.

-Vic vic cherubini
vikter@epicsoftware.com
====
Knows: Perl, HTML, JavScript, C/C++, PHP, Flash, Director
====
 
Sorry to rant, but... Why, oh why do people keep using PHP to do stuff that's easier and faster to do in the database? In this case you have tripled the overhead: two database queries and a random function in PHP.

You should really be doing it at the database level. Why select all that data into memory to manipulate when you only need a few records(or one)? MySQL has two ways of doing this, depending on your version.

In version 3.23 (current) you can just do something like
Code:
SELECT {columns} FROM table_name ORDER BY RAND() LIMIT {number of records}

In older versions, you have to do:
Code:
SELECT {columns}, id*0+rand() as rand_row FROM table_name ORDER BY rand_row LIMIT {number of records}
, where 'id' is your autoincremented primary key, and and rand_row is simply a variable you define to represent randomizing of the record id.

Then you can continue in PHP as if you had selected the whole table, but now you only have several random records to deal with. This will save a lot of I/O on your server, rather than doing it in PHP.

Remember that a database is a very powerful tool. Spend a bit of time learning what you can do with SQL, and you will be amazed. You might just cut your PHP code in half :).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top