1

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

7

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());
  • 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 Sep 8 '15 at 9:38
  • Sorry for off-topic, but what may be purpose of avoiding autoincrement? – ar7max Sep 8 '15 at 9:46
  • 1
    Because of the anonymous user @ar7max, that needs an ID of 0, so auto-increment isn't an option – Clive Sep 8 '15 at 9:47
  • But we still can create user, change id to 0 and reset autoincrement counter O.o – ar7max Sep 8 '15 at 9:51
  • 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 Sep 8 '15 at 9:52
3

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

2

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
}
  • That snippet is for VERY OLD Drupal 5 – user11153 Sep 8 '15 at 12:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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