Home > Net >  WordPress use wpdb -> update to update mutiple row
WordPress use wpdb -> update to update mutiple row

Time:06-18

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?

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 );
}

CodePudding user response:

You only need to set array index in 'update' and 'condition' like this -

global $wpdb;

$table_name = $wpdb->prefix . 'test';
    
$update = array(
    array( 'value' => 3 ),
    array( 'value' => 4, 'state' => 'asdf' )
);
    
$condition = array(
    array( 'name' => 'enable' ),
    array( 'name' => 'picked' )
);
    
for ( $i = 0; $i < sizeof( $condition ); $i   ) {
    $wpdb->update( $table_name, $update[$i], $condition[$i] );
}

This will update line by line.

  • Related