0

I'd like to do simple thing, but because of drupal serialized data field don't know how to. I'd like to set for every user a variable in "data" field, I do it manually when user edits its profile, like this:

$edit['data']['profile_bg_active'] = 1;

I want to do it now for all users, so the "profile_bg_active" exists in every user data field.

The code I am using is the following one.

$updateAllDudes = db_select('users', 'uu')
  ->fields('uu')
  ->execute();

foreach ($updateAllDudes as $dude) {
  $existingUser = user_load($dude->uid);
  $edit = array();
  $edit['data']['profile_bg_active'] = 1;
  user_save($existingUser, $edit);
}

I get the following error in the log:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name': INSERT INTO {users} (uid, name, pass, mail, theme, signature, signature_format, created, access, login, status, timezone, language, picture, init, data)`

It seems it is creating new users instead of updating the existing ones.

  • 1
    Bearing in mind that no-one's going to just write your code for you - what have you tried and what exactly doesn't work? – Clive Nov 26 '14 at 12:38
  • I have written all code for my users, used hook_user_presave, everything works fine. But I want now to set for everyone the "1" value. So should I iterate through every user account and do user_save, or can I edit this field doing SQL query? – Kretess Nov 26 '14 at 12:39
  • 1
    Which did you try? What happened? Did you get errors? – Clive Nov 26 '14 at 12:45
  • Welcome to Drupal Answers! This is a Q&A site, so the question needs to be separated from the answer. If you find the answer yourself, you are welcome to write the answer and accept it. In any case, the question should not contain the answer in itself; this is not a forum site. – kiamlaluno Nov 26 '14 at 13:24
1

This is because you're not filtering the users when you grab them using db_select. This will also grab the "Anonymous" user (uid 0). When you try to save that user, this error happens most likely. Putting a simple if(!empty($dude->uid)) within your foreach loop should fix this issue. Or excluding uid 0 from your db_select query using the NOT EQUALS condition like so:

$updateAllDudes = db_select('users', 'uu')
  ->fields('uu')
  ->condition('uid', 0, '<>')

Or by using the NOT IN condition:

$updateAllDudes = db_select('users', 'uu')
  ->fields('uu')
  ->condition('uid', array(0), 'NOT IN')

See here

if you need to edit all users (I am setting a default value for a custom field), you need to strip uid=0 from the list and deal with it as a special case.

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.