user6582353 user6582353 - 9 days ago 8
MySQL Question

Using MySQL UPDATE statement in Wordpress Php file

I have 1 field to update in Mysql database

table -> wp_usermeta

field -> meta_key: _ywpar_user_total_points

field -> meta_value: 4000


The update statement: UPDATE

wp_usermeta` SET `meta_value`= 15 WHERE `user_id`= 1 and `meta_key`="_ywpar_user_total_points"


I've already tried a bunch of code from Wordpress codex and Youtube and others website, like:

global $wpdb;
$wpdb->query
("
UPDATE $wpdb->wp_usermeta
SET meta_value = 7000
WHERE user_id = 1
AND meta_key = '_ywpar_user_total_points'
");





global $wpdb;
$wpdb->update(
'wp_usermeta',
array(
'meta_value' => 4000,
),
array(
'meta_key' => '_ywpar_user_total_points', 'user_id' => 1
),
array(
'%s', // value1
'%d' // value2
),
array( '%d' )
);





none of them are working

Answer

@user6582353 Here https://codex.wordpress.org/Class_Reference/wpdb is the ref.and syntax about how update work. see its syntax and understand it

$wpdb->update( 
    'table', 
    array( 
        'column1' => 'value1',  // string
        'column2' => 'value2'   // integer (number) 
    ), 
    array( 'ID' => 1 ), 
    array( 
        '%s',   // value1
        '%d'    // value2
    ), 
    array( '%d' ) 
);

Here %s is used for column1 value format which we are passing as string so provided %s and second column2 will be an integer type data so here taken %d.same way for where format too, in where passed only ID of integer type so provided %d only as last argument in array

Consider your case now

global $wpdb;
$wpdb->update( 
    'wp_usermeta', 
    array( 
        'meta_value' => 4000,
    ),
    array( 
        'meta_key' => '_ywpar_user_total_points', 'user_id' => 1
    ), 
    array( 
        '%s',   // value1
        '%d'    // value2
    ), 
    array( '%d' ) 
);

So here you are changing only 1 value which is integer and the second is where format where you are taking 2 arguments 1 is of string and second is of integer so the final syntax would be something like

 global $wpdb;
    $wpdb->update( 
        'wp_usermeta', 
        array( 
            'meta_value' => 4000,
        ),
        array( 
            'meta_key' => '_ywpar_user_total_points', 'user_id' => 1
        ), 
        array( 
            '%d'     // for meta_value
        ), 
        array( 
            '%s',   // for meta_key
            '%d'    // for user_id
        ) 
    );

Hope its clear to you now and works for you.