• Resolved skalibran

    (@skalibran)


    Hey there,

    for a project, I added a new row to the wp_users table called ‘buildings’. Using wpdb, I want to update the values of this row. Maybe I’m dumb, maybe it was just a hard day, but I can’t get my code working:

    $table = 'wp_users';
    $data = 'agdweft'; // My head on the keyboard, told you it was a hard day :D
    $where = 'buildings';
    $wpdb->update( $table, $data, $where);

    That is based on the example:
    <?php $wpdb->update( $table, $data, $where, $format = null, $where_format = null ); ?>

    https://codex.wordpress.org/Class_Reference/wpdb#UPDATE_rows

    I’m sure the connection is working fine, reading the values does not make any problems.

    What am I doing wrong?

    Thanks for reading!

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator bcworkz

    (@bcworkz)

    $data and $where must always be associative arrays where the column name is the array key name. Read the argument descriptions a little more carefully. See the example at the end of the section.

    Since you’ve had a hard day, you’re excused for not RTFM 🙂

    Thread Starter skalibran

    (@skalibran)

    Hey, thanks for the answer. I think I understand now how it works. Let’s forget the ‘where’, not needed right now. What did I wrong?

    I’m not so much into php right now, maybe its simple and I’m just too inexperienced (dumb) ^^.

    $table = 'wp_users';
    $data = array('buildings' => 'agdweft');
    $wpdb->update( $table, $data['buildings']);

    Moderator bcworkz

    (@bcworkz)

    Use $data without specifying the buildings key in update, the method will use whatever is in the array, being more specific confuses it.
    $wpdb->update( $table, $data );

    Not dumb, just confused over unfamiliar syntax 🙂 When you specify an array key you are passing a single value. You must pass an entire array even if it only has the one key/value pair. I hope this might start to make sense.

    Dion

    (@diondesigns)

    Rows in tables don’t have names. When you added this “buildings” row to the wp_users table, what exactly did you add? Was “buildings” the login name?

    Now, if what you did was add a column to wp_users, then we’re talking about something completely different. And if so, you will need to add the following line in wp-config.php:

    define('DO_NOT_UPGRADE_GLOBAL_TABLES', true);

    Without this line, WordPress would delete your new column during a core update. The above line will stop WordPress from running the dbdelta anti-feature on your tables.

    Thread Starter skalibran

    (@skalibran)

    Yes, I was completely unfamiliar with the syntax 😀 It is working now, awesome! Thanks for your help.

    Also thanks to Dion for the little reminder, I hope with that snippet my changes to the database structure of wordpress are safe. 🙂

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘How to update values with wpdb’ is closed to new replies.