Add value to every user in data field 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')
  -&gt;fields('uu')
  -&gt;execute();

foreach ($updateAllDudes as $dude) {
  $existingUser = user_load($dude-&gt;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.
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-&gt;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')
  -&gt;fields('uu')
  -&gt;condition('uid', 0, '&lt;&gt;')


Or by using the NOT IN condition:

$updateAllDudes = db_select('users', 'uu')
  -&gt;fields('uu')
  -&gt;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.