I've been searching for almost an hour on the forums looking for the answer to this, and evidently I'm not wording my searches correctly because I haven't found a solution, even though I know I've come across this here before.
I have a database with a table for users. In this users table is a "user_code" field. The table essentially looks thus:
user_id user_code user_name user_email
-------------------------------------------------------------
0001 1001 Bob bob@email.com
0002 1002 Rick rick@email.com
0003 1003 Tom tom@email.com
0004 1004 Alan alan@email.com
Now currently what I have when a new user is added is an INSERT statement that includes a variable result from a previous query using the MAX() function to get the next available user_code, like this:
$cd = "SELECT MAX(user_code) FROM users";
$cd_result = @mysql_query($cd, $connect) or die(mysql_error());
while ($cd_row = mysql_fetch_array($cd_result)) {
$cd_code = $cd_row['MAX(user_code)'];
$cdcode = ($cd_code + 1);
}
$nu = "INSERT INTO users (user_code, user_name, user_email) VALUES ('$cdcode', '$_POST[username]', '$_POST[email]')";
$nu_result = @mysql_query($nu, $connect) or die(mysql_error());
Naturally, after the first time a previously entered user was deleted, this approach presented a problem.
So what I need to do is re-phrase the SELECT statement to be able to loop through the user_code fields and grab the next available unused user_code. For example, if I deleted the user "Tom" above, and then later added a new user to the database, my SELECT statement will show the next available user_code as 1005, when it should be 1003 ("Tom's" old number).
I'm fairly certain the solution here is to utilize an array of some sort... but I'm not too familar with arrays (other than what's shown above), and as such am not sure how to begin. I'd really appreciate any ideas.