I am using this code.

function MY_MODULE_comment_presave($comment) {
  $name = 'test';
  $email = 'test@test.com';
  $password = user_password(8);
  $fields = array(
    'name' => $name,
    'mail' => $email,
    'pass' => $password,
    'status' => 1,
    'init' => '',
    'roles' => array(
      DRUPAL_AUTHENTICATED_RID => 'anonymous user',
  $account = user_save('', $fields);

I get the following error.

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name': INSERT INTO {users}

How do I solve this error?


There are some errors in the code you are using, but the main error, which is causing the error message you quoted is that the code is creating users always with the same username, which is not allowed in Drupal: Every user needs to have a unique username.

If you are showing exactly all the code you are using for that hook, it's not clear why you keep creating an account before a comment is saved. You aren't checking which user is creating the comment, which means the user account is created even if the comment is created from the admin user.

To avoid that error message, you need to first verify the account you are going to create doesn't already exist, or you create a different username every time a comment is created. (It doesn't make sense, though.)

In the first case, you use user_load_by_name() passing the username; if the function returns FALSE, it means a user with that username doesn't exist, and it can be created.
In the second case, you just add a random number to the username, to make it unique; even in this case, I would verify there isn't already an account with that username.

As for the other errors:

  • The roles array should be the following one:

    'roles' => array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
  • The first argument of user_save() is an object, not an empty string, for example the value returned from new stdClass()

| improve this answer | |
  • Thanks for your answer. I am using unique user name only, whenever anonymous user created comment it automatically create a user in back-end. i tried user_load_by_name() condition also, but i get same error. – Kamalakkannan Jun 12 '17 at 11:28
  • There is also another problem with your code, since the error is complaining about '' (the empty string) being used as username. – kiamlaluno Jun 12 '17 at 12:16

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.