Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm trying to update user_login in the wp_users table, to force update a user's username to their email address on submission of a front end edit profile form.

I know WordPress forbids this via the wp_update_user function so I am trying to use SQL with wpdb functions.

Here is what I have, and it is not working :(

global $wpdb;
$tablename = $wpdb->prefix . "users";
$sql = $wpdb->prepare( "UPDATE ".$tablename." SET user_login=".$user_email." WHERE ID=".$user_id."", $tablename );
$wpdb->query($sql);

Can anyone help?

Fixed it, see here: https://gist.github.com/4045215

share|improve this question
add comment

2 Answers

First:

The $wpdb object has the names of tables, with prefixes, pre-defined for you.

$wpdb->users == 'wp_users'
$wpdb->posts == 'wp_posts'
etc.

Second:

$wpdb-prepare() is essentially a WordPress aware printf, if you pass it more than one argument, you need to have some string/digit replacements %s %d

$sql = "UPDATE {$wpdb->users} SET user_login = %s WHERE ID = %d"
$sql = $wpdb->prepare($sql, $user_email, $user_ID);
$wpdb->query($sql);

Alternatively $wpdb does have an update method as well:

$wpdb->update($wpdb->users,
    array('user_login', $user_email), array('ID', $user_id),
    array('%s'), array('%d'));

http://codex.wordpress.org/Class_Reference/wpdb

share|improve this answer
add comment

Fixed it! There are two methods:

// Force update our username (user_login)
global $wpdb;
$tablename = $wpdb->prefix . "users";

// method 1
//$sql = $wpdb->prepare("UPDATE {$tablename} SET user_login=%s WHERE ID=%d", $user_email, $user_id);
//$wpdb->query($sql);

// method 2
$wpdb->update( $tablename, array( 'user_login' => $user_email ), array( 'ID' => $user_id ) );

Updated Gist: https://gist.github.com/4045215

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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