Jump to content

Randomizing the items coming from the database


divinedesigns1

Recommended Posts

how can i randomized the id coming from the database? i try str_shuffle and shuffle, but those isnt exactly what im trying to do, is there another way of doing this?

Link to comment
Share on other sites

Do you mean to randomize the order of the records? Or to retrieve a random record from the database?

 

To retrieve multiple random rows efficiently is a bit complicated. Here's what seems to be a solution:

http://snippetsofcode.wordpress.com/2011/08/01/fast-php-mysql-random-rows/

I don't recommend using the mysql PHP extension as that example does, use MySQLi or PDO.

 

To look for a single random row is simpler:

1. First determine how many rows there are:

SELECT COUNT(*) AS numRows FROM data 

2. Store the result in a PHP variable, $numRows.

3. Make a PHP variable with a random number:

$rand = mt_rand(0, $numRows);

4. Then search for the row with that number

SELECT * FROM data LIMIT $rand, 1
  • Like 1
Link to comment
Share on other sites

There are major problems with ORDER BY RAND(). If the table is large the query can run really slow because it has to manipulate every single row of the table at once.

Here's an article about it:

http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/

  • Like 2
Link to comment
Share on other sites

ORDER BY RAND()

ORDER BY RAND() would take too long, according to what i have readed so far

 

 

Do you mean to randomize the order of the records? Or to retrieve a random record from the database?

 

To retrieve multiple random rows efficiently is a bit complicated. Here's what seems to be a solution:

http://snippetsofcode.wordpress.com/2011/08/01/fast-php-mysql-random-rows/

I don't recommend using the mysql PHP extension as that example does, use MySQLi or PDO.

 

To look for a single random row is simpler:

1. First determine how many rows there are:

SELECT COUNT(*) AS numRows FROM data 

2. Store the result in a PHP variable, $numRows.

3. Make a PHP variable with a random number:

$rand = mt_rand(0, $numRows);

4. Then search for the row with that number

SELECT * FROM data LIMIT $rand, 1

i will try this and get back to you with the results, appreciate all the help

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...