N00b
N00b

Reputation: 149

Doing basic math with database values

Completely suprised how I don't know how this should be done.

All I need is to add 1 to database value (not to show it as [0, 1] but literally add (+) 1)

Im using WordPress but this should make no difference.

Functions Im using:

update_user_meta($user_id, $meta_key, $meta_value);

My logic says that I need to retrieve the value, add it & then update but isn't there an easier way?

How this would look:

//Get the value from database
$meta_value = get_user_meta($user_id, $meta_key);
//Math
$meta_value = $meta_value + 1;
//Update the value in database
update_user_meta($user_id, $meta_key, $meta_value);

Upvotes: 0

Views: 59

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167192

You can easily do a single step one:

update_user_meta($user_id, $meta_key, intval(get_user_meta($user_id, $meta_key)) + 1);

The intval function gets the integral value of the expression and adding 1 to it will set it accordingly. Hope this helps.

Or, if you would like to directly deal with the database, you can do something like this, but beware, it has to get the correct database substitutions like wp_, etc:

UPDATE `wp_usermeta`
  SET `meta_value` = `meta_value` + 1
  WHERE `user_id` = $user_id
  AND `meta_key` = $meta_value;

Upvotes: 3

Related Questions