Make WordPress Core

Opened 8 years ago

Last modified 7 years ago

#39748 new enhancement

Function to insert or update DB value

Reported by: tazotodua's profile tazotodua Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: Database Keywords:
Focuses: Cc:

Description

Hello.
I have been searching for long and couldnt found a good solution to the simple problem:

lets say,in my plugin, I create a new table.
Then I want to have a function, that updates a row in table, which's column (named EventId) equals i.e. 734 (if such row not exists, then create it).

for that, I use my custom-created function:

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

usage:

 UPDATE_OR_INSERT('my_table',  array('new_page_content'=>'blabla'),   array('EventId'=>734));

it's good if there was built-in function that replaces this custom method

Change History (3)

#1 @SergeyBiryukov
8 years ago

  • Component changed from General to Database

#2 @SergeyBiryukov
8 years ago

  • Type changed from defect (bug) to enhancement

#3 @tazotodua
7 years ago

any news?

Note: See TracTickets for help on using tickets.