I need to generate a unique random code to store in a database with a user id.
What I’m trying to do is create a php script that first generates a random string of a given length, then checks a database to see if that string already exists, if so, generate a new random string.
The database will be organized by email address or some other field like customer_id. Each user can have say up to 5 devices associated with their account.
As a test I’ve created two MYSQL tables, one called users: email, firstname, lastname
the other called udevices. Udevices has 6 fields, one for the email address and 5 for the devices: email, dev1, dev2, dev3, dev4, dev5
all fields in both tables are VARCHAR
It occurs to me that another way to organize this is to have just two fields – email and device and then for each device just add another record to devices. Not sure which is most efficient.
So what i’m looking for is how to write a SELECT statement that will query the database for a given email address and a device string.
So, to boil the question down:
Can someone give me an example of a SELECT statement as described above? Is this even possible? Web searches on the topic bring up people talking about having to loop through each db record. Is that the only way, and if so, can someone give me an example of a PHP script that can loop through each record to check if a string already exists in a database?
You need a minimum of two tables, but most probably three if you need device descriptions, etc… I would go with three tables if I were you.
users:
user_id | email | name | surnamedevices:
device_id | device_name | ...user_devices:
user_id | device_idOn
usersanddevicestheuser_idanddevice_idmust be the primary keys. Onuser_devicesuser_idanddevice_idmust be the compound primary key.Then the query to select all the devices of a user would be:
As far as the unique random code, you must tell us what its content will be (i.e. where will the uniqueness be based upon). If you have that, you can easily use one of the hashing functions such as
md5(), etc… to generate the random string.EDIT
If you do not need to verify the value of the random string, then you can generate one with the
base_convertandmicrotime. The odds of duplicates are down to the microsecond. That is, if both visitors will request the code on that same microsecond they will get the same string, which is hardly ever the case, but still possible.