Support » Developing with WordPress » Use wpdb -> update to update mutiple row

  • I’m trying to update multiple rows once, I use the array to store the data and I use for loop to try to update the data but it’s not working because the data in the database is still the same. What am I doing wrongly? Or is there any better way to do this?

    
    global $wpdb;
    
    $table_name = $wpdb -> prefix . 'test';
    $check_first = 1;
    $check_second = 2;
    $update = array (
       array ( 'value' => $check_first ),
       array ( 'value' => $check_second )
    );
    $condition = array (
       array ( 'name' => 'enable' ),
       array ( 'name' => 'picked' )
    );
    
    for ( $x = 0; $x <= 2; $x++ ) {
       $wpdb -> update ( $table_name, $update, $condition );
    }
Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    update() is intended to update one row at a time. The passed arrays are supposed to be column => value pairs of data. Passing nested arrays is beyond the method’s ability to handle.

    What you could do is create a source data array where each element is the $data and $where args appropriate for a single row’s update. Loop through the array with foreach(), passing $data and $where sub-elements to update().

    A single element in this source data array might look like this:

    array(
      'data' => array ( 'value' => 1, ),
      'where' => array ( 'name' => 'enable', ),
    ),

    Let’s say the source data array is assigned to $updates. Your loop code could be something like:

    foreach ( $updates as $update ) {
      $wpdb -> update ( $table_name, $update['data'], $update['where'] );
    }

    This of course will execute one query for every element in the source data array. If you really need to update multiple rows with one query, you’d need to create your own SQL and execute it with $wpdb->query().

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.