scriptygoddess

02 Jun, 2004

Random with MySQL

Posted by: Jennifer In: Script snippet

I have a random quote and also a random link on my sidebar. Since I have 99 links and 190+ quotes, it was easiest to use a MySQL db to manage it. This is the query I was using:

$sql = "SELECT * FROM blogroll ORDER BY rand() LIMIT 1";

The problem I had was that it wasn't really random. When I had about 10 links in my blogroll, I hit refresh 80 times and got the first entry EVERY TIME. It worked better when I had more entries, but I still got that first one way too often. I tried to use the mt_rand() function, but it wouldn't work in the query. I had create a variable that used mt_rand() to pick a number within my range and then call that id in the query. So when I deleted a link or added a new one, it broke.

Then I found the following on php.net:

$sql = "SELECT * FROM blogroll ORDER BY rand(" . time() . " * " . time() . ") LIMIT 1";

This works MUCH better, and it's showing a lot of links and quotes that almost never showed up before. Hope that helps someone!

1 Response to "Random with MySQL"

1 | powerpop

June 22nd, 2004 at 8:29 pm

Avatar

thanks a ton – this little code nugget helped a lot – i will post back when my service is live – i bet it is something you will want to use here!

Featured Sponsors

Genesis Framework for WordPress

Advertise Here


  • Scott: Just moved changed the site URL as WP's installed in a subfolder. Cookie clearance worked for me. Thanks!
  • Stephen Lareau: Hi great blog thanks. Just thought I would add that it helps to put target = like this:1-800-555-1212 and
  • Cord Blomquist: Jennifer, you may want to check out tp2wp.com, a new service my company just launched that converts TypePad and Movable Type export files into WordPre

About


Advertisements