• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Database Helper & Conditions

#1
[eluser]austintbiggs[/eluser]
I'm currently working on a membership feature of my website. Specifically I've tried a few combinations and I'm still struggling.

The feature includes a unique user id (6 digit) created by the mt_rand function; what I'm stuck on is the conditional statement to check the database to see if the number already exists inside the table 'membership' and if so generate a new number and recheck the table, continuously looping until a unique number has been generated then store it as a key 'userID'.

Essentially (Or something of the sort):

Code:
$user_id = mt_rand(000001, 999999);
if $user_id exists within membership
$user_id = mt_rand(000001, 999999);
$insert = $this->db->insert('membership', $user_id);

Any and All help is appreciated [:

#2
[eluser]clutton[/eluser]
Here are a couple ideas:

1) If the table with User_id then perhaps you could use an auto increment.

2) If you have no control over then perhaps you could make them all sequential... ie select the max number from the user_id column to be used as the new one.


Cory L

#3
[eluser]Nick_MyShuitings[/eluser]
Agreed with clutton, unless you have a really good reason for wanting to do that, it doesn't seem the most elegant solution when mysql has built in function to auto increment and set it as a primary key will impede duplicates.

#4
[eluser]InsiteFX[/eluser]
If you can not do any of the above then you can try this!
Code:
$this->db->where('user_id', $user_id);
$query = $this->db->get('membership');

if ($query->num_rows() == 0)
{
    // the user_id does not exist.
}
else
{
   // the user_id exists so create a new one
}

InsiteFX


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.