Dealing with deleted records in mysql. It breaks my PHP loops...

Associate
Joined
15 Feb 2006
Posts
1,872
Location
hell
Hi guys,

I'm building a site at the moment that has a mysql table containing rows of data with 3 columns: id, name, url. The ID field is set to auto-increment in this case.

On my webpage I'm trying to pull out 5 random entries from the database, and print some text to a page. I've built some code to generate 5 random numbers between 1 and the maximum amount of rows in the table. But there's a problem here, if someone deletes one of the records...

Let's say I have 3 rows:

1 armyofharmony www.armyofharmony.com
2 overclockers www.overclockers.co.uk
3 bbc www.bbc.co.uk

If I delete record 2 (overclockers) and try and pick random entries from here, the table will look like this:

1 armyofharmony www.armyofharmony.com
3 bbc www.bbc.co.uk

If my code then picks the number "2" and I query the database for sites with ID == 2 it won't work.

I figure I need to do my selection based on row number, instead of unique ID. From what i've googled this might not be the best approach.

Can anyone help me with this?

What's annoying is that I think I'm only suffering here because I'm using random IDs. If I just had to continually loop through 5 times I wouldn't need to care about the ID.

I'm picking the ID in advance using PHP so that the process is quicker than selecting it using mySQL.

Cheers
 
Hi Moogle

I'm not sure you can run a MYSQL select based on row number... that's the bit I'm getting stuck on.

Basically I've counted the rows and am picking random numbers from the rows... but if my IDs for each record do not correspond to the rows, it won't work!

Cheers
 
I think if I first run a query to create an array with all the IDs available, then select 5 IDs at random from there it might work... Just googling around to see if it's possible
 
Hi Thrash

The reason I've avoided that approach is that I've heard it can take a long time to retrieve results. From what I've read online, it's better to pick the actual record you want before doing the query - it can massively increase speed

Cheers
 
Back
Top Bottom