Opened 9 years ago
Last modified 9 years ago
#39748 new enhancement
Function to insert or update DB value
| Reported by: | tazotodua | Owned by: | |
|---|---|---|---|
| Priority: | normal | Milestone: | Awaiting Review |
| Component: | Database | Version: | |
| Severity: | normal | Keywords: | |
| Cc: | Focuses: |
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)
Note:
See TracTickets
for help on using tickets.
![(please configure the [header_logo] section in trac.ini)](/chrome/site/your_project_logo.png)
any news?