• I’m trying to write a variable to the wp database. I’ve got a forum successfully setup so that a user inputs a value, and that value is then serialized and stored in a variable.
    However I haven’t been able to get the $wpdb command to work. I’m not even sure if it’s being executed or not.

    if (isset($_POST['save_membership_details'])) {
    $wpdb->sql = "UPDATE 'wp_usermeta', SET 'wp_value' = '" .$serial. "', WHERE 'user_id' = '" .$current_user -> ID. "'";}
    $selection = $_POST['membership'];
    $value = array ($selection => true,);
    $serial = serialize($value);
Viewing 4 replies - 1 through 4 (of 4 total)
  • Firstly, you’re creating the variables after you’re attempting to add them into the DB… that’s never going to work. You need to get the value and then add it into the DB.

    Secondly, you’re code above updates every meta value for that user as the only constraint is the user ID, not the meta key. I’m sure that’s really not what you want.

    Thirdly, you need to look at the column names. There’s no column called wp_value in the wp_usermeta table, so you’ll get an error becuase your query is trying to reference an invalid column name.

    Forth, you’re wide open to SQL injection attacks becuase you’re not escaping any variables. If you’re going to do it this way, look at $wpdb->prepare() to find out how to do it correctly.

    To do it the “right” way you would use $wpdb->update(). Something like this…

    $selection = $_POST['membership'];
    $value = array ($selection => true,);
    $serial = serialize($value);
    
    if (isset($_POST['save_membership_details'])) {
    
        $wpdb->update( array(
            $wpdb->usermeta,
            array(
                'meta_value' => $serial
            ),
            array(
                'user_id' => $current_user->ID,
                'meta_key' => 'your_key_name'
            )
        ));
    }

    Note that using this function you don’t need to escape the variables as that’s done internally by the update() function.

    This is not really an answer to your question, but I think you are probably looking for this:
    https://codex.ww.wp.xz.cn/Function_Reference/add_user_meta

    Check out the Related section for other relevant functions.

    (After I wrote this, I see that you have been given a more direct answer)

    jonradio is right too! But, I’d suggest using update_user_meta() as that will add in the value if it doesn’t exist, and update if it exists already.

    Thread Starter WindyPoint

    (@windypoint)

    Thanks for the replies! I’ll post how it goes.

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Need help writting variable to database’ is closed to new replies.