View Full Version : Pick x number of rows from mysql table and display with php

03-30-2013, 08:26 PM
Hi all,
i am currently designing the welcome page for my website and i would like to display random images from my database on the home screen.
i have many images stored in my database and each time someone visits the site i would like 4 random pictures to be selected from my db and displayed. i have heard about the rand() php function but heard that for large databases this is a bad one to use.
i really am stumped on this, thanks in advance to anyone who can help :):confused:

Old Pedant
03-31-2013, 12:19 AM
"large" means hundreds of thousands or millions of records.

I doubt seriously that you have that many images in use.

I would feel comfortable using RAND() with up to a few thousand records, though if your tables are "wide" (that is, if there are many many fields in each row of the table) there are some tricks you might want to use to improve the efficiency of your queries.

Old Pedant
03-31-2013, 12:22 AM
For example, if you have an ID column as your PRIMARY KEY, you could do:

SELECT * FROM yourtable
SELECT id FROM yourtable

That way the ORDER BY part of the query only has to fetch the IDs (presumably from the index, without touching the table, per se), pick 4 of them at random, and only then do you pick 4 full records from the entire table.