Want a random code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
hesham2012
Forum Newbie
Posts: 8
Joined: Fri Mar 09, 2007 11:34 pm

Want a random code

Post by hesham2012 »

i have a database table contains many numbers from 1 : 200 a want to generate a random code between 1 : 200 but this code must be different than others in database !how come?
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

How come? Not sure. It's your idea.

You want the number to be IN the database, or you just want to make a random number, then check if it's there?
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

There are several ways to go about this, ranging in complexity and performance.

One simple, easy way of implementing this is simply generating a number from 1 to 200 and then doing it again if you get a unique key violation. Of course, you run a very high risk of collision once you start generating an appreciable amount of numbers.

You could also select all rows from the database, invert it, and generate a random key from that set.

I wonder why 200 though: that's very small, and it'll be filled up in no time.
User avatar
nathanr
Forum Contributor
Posts: 200
Joined: Wed Jun 07, 2006 5:46 pm

Post by nathanr »

i don't really understand but.. you could always use the mysql solution to return 1 row from the table

SELECT * FROM tablename ORDER BY RAND() LIMIT 1

I'm sure it's rand?? although check the mysql manual - if indeed this is what you mean
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

nathanr, I'm fairly certain your query works, but it specifically selects a row that does exist: this guy wants the converse.
Post Reply