0

am trying to update multiple fields in a database using their respective meta key but it doesn't work. It works only when I update them one at a time. How do I it to update multiple fields?

Below works:

$sql = "UPDATE wp_usermeta SET meta_value = '$meta_value' WHERE meta_key = '$meta_key' AND user_id= $user_ID";

Below does not work:

$sql = "UPDATE wp_usermeta SET (meta_value = '$meta_value', meta_key = '$meta_key'), (meta_value = 'The freak I wants', meta_key = 'on_the_weekends_i' WHERE user_id= $user_id)";
Difster
  • 3,264
  • 2
  • 22
  • 32
Sleek Geek
  • 4,638
  • 3
  • 27
  • 42
  • Possible duplicate of [How to update user meta for multiple meta\_key in wordpress](https://stackoverflow.com/questions/30610780/how-to-update-user-meta-for-multiple-meta-key-in-wordpress) – Difster Jul 09 '17 at 06:06

2 Answers2

0

Please try this :

    $metaInfo= [
         [
            'meta_key'=>$meta_key,
            'meta_value'=>$meta_value,

          ],
          [
            'meta_key'=>'another key',
            'meta_value'=>'another value',

          ],
          [
            'meta_key'=>'another key 1',
            'meta_value'=>'another value 1',

          ]
        ];

        foreach($metaInfo as $info){
          foreach($info as $field => $value){
            $sql= "UPDATE wp_usermeta SET ($field='$value') WHERE user_id=$user_id";
           //execute here your query
            }


        }
M.Islam
  • 151
  • 2
  • 7
  • Did u execute your query. ? I just give you the main functionality code . You have to execute $sql query. What is error ? – M.Islam Jul 09 '17 at 06:32
  • Can u give your code to see that, how u execute the query. – M.Islam Jul 09 '17 at 06:45
  • You have to execute query within foreach($info as $field => $value){ $sql= "UPDATE wp_usermeta SET ($field='$value') WHERE user_id=$user_id"; } this block – M.Islam Jul 09 '17 at 06:53
0
UPDATE wp_usermeta SET meta_value = CASE
    WHEN user_id = 1 THEN 329152
    WHEN user_id = 2 THEN 349325
    WHEN user_id = 3 THEN 111592
    ELSE meta_value
    END
WHERE user_id  in (1,2,3)

Here is how to do bulk update in MySql

user1599755
  • 149
  • 1
  • 6