Take the 2-minute tour ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

I'm inserting new users into tables users (using a webservice that insert), but how to make uid being automatically inserted and it would be always the next value of the current maximal value on table users (and auto-increment too) ?

Thank you

share|improve this question

3 Answers 3

The users table doesn't have an auto-increment constraint on the primary key (or any field).

The recommended way to add users is using the API (user_save() etc), that will handle the ID for you.

Failing that, just query for the maximum ID in the table before you perform the insert; after the first insert, assuming you have exclusivity on this database while you're developing, you can maintain the increment in your code (no need to check the table each time).

Drupal does exactly the same thing in user_save():

$account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());
share|improve this answer
    
Hi @Clive, thank you for your helpful answer ,as always, I didn't mentioned in my question that i've tested inserting using max + 1 in another query that fetch users etc.. So i'll keep it right now because as you said user_save do the same, so thank you –  Mitch 19 hours ago
    
Sorry for off-topic, but what may be purpose of avoiding autoincrement? –  ar7max 19 hours ago
1  
Because of the anonymous user @ar7max, that needs an ID of 0, so auto-increment isn't an option –  Clive 19 hours ago
    
But we still can create user, change id to 0 and reset autoincrement counter O.o –  ar7max 19 hours ago
    
Can do, but one might consider that to be doing things the wrong way round. There may be other reasons I'm not aware of/have forgotten, but that's the one that sticks out in memory –  Clive 19 hours ago

Use user_save()

and try to avoid direct db_insert for new user creation. With direct db_insert you cut off the whole functionality of Drupal and other Modules

share|improve this answer

you can enter new user using user_save()

$account = (object) array ();
$options['name'] = $username;
$options['mail'] = $email;
$options['pass'] = md5($passwd);
$result = user_save($account, $options);
if ($result === FALSE) {
   //take some action
} else {
   //$result is the loaded user object
}
share|improve this answer
    
That snippet is for VERY OLD Drupal 5 –  user11153 16 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.