[wp-trac] [WordPress Trac] #39748: Function to insert or update DB value
WordPress Trac
noreply at wordpress.org
Tue Jan 31 10:00:02 UTC 2017
#39748: Function to insert or update DB value
--------------------------+-----------------------------
Reporter: tazotodua | Owner:
Type: defect (bug) | Status: new
Priority: normal | Milestone: Awaiting Review
Component: General | Version:
Severity: normal | Keywords:
Focuses: |
--------------------------+-----------------------------
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:
{{{#!php
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
--
Ticket URL: <https://core.trac.wordpress.org/ticket/39748>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list