Skip to content

Instantly share code, notes, and snippets.

@samueleastdev
Last active February 17, 2017 16:55
Show Gist options
  • Select an option

  • Save samueleastdev/c9b0b4e412e6c7d97f51040aa3cb62bd to your computer and use it in GitHub Desktop.

Select an option

Save samueleastdev/c9b0b4e412e6c7d97f51040aa3cb62bd to your computer and use it in GitHub Desktop.
WordPress Insert or Update statement
function update_globals(){
if (!is_user_logged_in()) exit();
global $wpdb;
$doesExist = $wpdb->get_row( "SELECT * FROM table WHERE id = " . get_current_user_id() );
// Update array
$upValues = isset($_REQUEST) ? $_REQUEST : false;
// unset values if needed
//unset($upValues['action']);
if(false === $upValues){
echo json_encode(array(
'error' => true,
'message' => 'No values sent to the request'
));
}
if(!empty($doesExist)){
$query = $wpdb->update(
'table',
$upValues,
array( 'id' => get_current_user_id() )
);
if(false === $query){
echo json_encode(array(
'error' => true,
'message' => 'There has been a error'
));
}else{
echo json_encode(array(
'error' => false,
'message' => 'Successfully updated'
));
}
}else{
// Add the user id to array
$upValues['id'] = get_current_user_id();
$query = $wpdb->insert(
'table',
$upValues
);
if(false === $query){
echo json_encode(array(
'error' => true,
'message' => 'There has been a error'
));
}else{
echo json_encode(array(
'error' => false,
'message' => 'Successfully inserted'
));
}
}
die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment