So, let’s say I’ve got a queryable database with 100 data objects in it. I want to show 3 random ones.
I don’t have any working code since this is an idea I just had.
Method 1:
- Query Database for 3 random ids using
mt_rand()
so essentially Query for IDs (1, 15, 67) then print each one.
OR
Method 2:
- Use
mt_rand()in the loop with a counter ($counter = 0; $counter = ++$counter)
essentially Query ALL posts if (ID = 1, 15, 67) then print each one and if ($counter = 3){ break; }
Method 2 sounds like it would give me a nasty large object. While Method 1 sounds like it would be a more expensive DB query. I think Method 1 would be better, but I’m not sure
If your ID column is indexed, which it probably should be, then doing a select with
is very cheap. And it will scale even if you have many more rows in your table. Solution 2 will not scale as it selects the whole table and loads it into memory.