How to use update and delete query in wordpress

About UPDATE+INSERT:

I have made a function for myself, and might help you too, i.e. :

UPDATE_OR_INSERT('wp_users',  array('gender'=>'female'), array('name'=>'Monika') );

that will UPDATE A VALUE in column (where name=monika), but in case that value doesnt exists, then it creates a new record in DB.
Why this is necessary? because As far as i know, there is no sophisticated WP function, that will update data in DB (if value exists) or inserts data (if not exists). Instead, we use : $wpdb->update() or $wpdb->insert().
So, use that function, it helps:

function UPDATE_OR_INSERT($tablename, $NewArray, $WhereArray){          global $wpdb; $arrayNames= array_keys($WhereArray);
    //convert array to STRING
    $o=''; $i=1; foreach ($WhereArray as $key=>$value){ $o .= $key . ' = \''. $value .'\''; if ($i != count($WhereArray)) { $o .=' AND '; $i++;}  }
    //check if already exist
    $CheckIfExists = $wpdb->get_var("SELECT ".$arrayNames[0]." FROM ".$tablename." WHERE ".$o);
    if (!empty($CheckIfExists))  { return $wpdb->update($tablename, $NewArray,  $WhereArray );}
    else                         { return $wpdb->insert($tablename,     array_merge($NewArray, $WhereArray) );  } 
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)