Recommended:

  • phpclasses.org
  • jsclasses.org
  • jsmag.com
  • siteapps.com
  • View our reviews on Hot Scripts
  • JS Tutorial
  • scripts.com
  • securesignup.com




Recent Comments

Powered by Disqus




Back to articles

Select random row faster

Selecting random row from mysql usual way is too slow, especially on tables with a lot of rows, because mysql needs to create temporary table. So never do ti this way:

SELECT * FROM table_name ORDER BY RAND() LIMIT 1

It is much better to choose random number in php and then select row with that number. Of course you should know how many rows are there:

<?php

$query = "SELECT FLOOR(RAND() * COUNT(*)) AS random_row FROM table_name";

$result = mysql_query($query);

$row = mysql_fetch_array($result);

$query = "SELECT * FROM table_name LIMIT ".$row['random_row'].", 1";
?>

You may also be interested in:

Powered by BlogAlike.com

blog comments powered by Disqus