3

I am using the following code to add a user:

  $roles = user_roles();
  $userinfo = array(
  'name' => 'user2',
  'pass' => '123456',
  'init' => 'user2d',
  'status' => 1,
  'access' => REQUEST_TIME,
  // This is where we are different from the default function.
  'roles'        => array(array_search('student', $roles) => 6),

);
$account = user_save(drupal_anonymous_user(), $userinfo);

I am getting this error message:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 19 column name is not        unique: 
INSERT INTO {users} (uid, name, pass, created, access, status, init) VALUES (?, ?, ?, ?, ?, ?, ?); Array ( [0] => 15 [1] => user2 [2] => $S$DrkIg0KuBFO12eQ9nQ5ViSx4ydfcWS0nS1TMvaTjYyZyfmVniGgh [3] => 1333135061 [4] => 1333135061 [5] => 1 [6] => user2d ) in drupal_write_record() 
(line 6975 of 

I am wondering if someone can explain what is going wrong with me trying to add a role. ......

5

drupal_anonymous_user() gives you an object with a uid that is considered empty by PHP. This means, your call to user_save() will try to insert a new user into the database. The insert operation fails, because a user with the name user2 already exists in the database.

1
  • thank you that was a very clear and concise answer. I will remember when i see that error again what to look for.
    – Alexander
    Mar 30 '12 at 21:24

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.