Simple PHP MySQL Class

That’s right! I have a simple MySQL class file that you can use in your PHP projects. I’ve been using it for years, and it’s never let me down!

You can grab it on my Github: http://github.com/a1phanumeric/PHP-MySQL-Class.

Read More…

Posted in Featured, MySQL, PHP at August 17th, 2010. 7 Comments.

Get Random Row with MySQL Without ORDER BY RAND()

This is an update to a previous post of mine which uses the RAND() method. Using the following code, you can retrieve a random row much, much faster (MySQL 4.1.x/5.0.x), with thanks to Jan Kneschke:

SELECT FROM

AS r1
JOIN (SELECT ROUND(
RAND( ) * (
SELECT MAX( id ) FROM
)
) AS id
) AS r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 1;

Replace:

  • <COLUMN> with the name of the column(s) you wish to retrieve
  • <TABLE> with the name of the table you wish to retrieve the data from

I've tested this with a table with over 660,000 records, and got a response in 0.0200 seconds, whereas with ORDER BY RAND() i got a response in 2.1599 seconds.

Total Number of Rows:

Cardinality

Old Method:

Old Method

New Method:

New Method

Posted in Featured, MySQL at March 5th, 2008. 14 Comments.