Simple Update

  global $wpdb;
  $sql = $wpdb->prepare("UPDATE {$wpdb->prefix}tbl_my_table SET
						my_fieldname1 = 123,
						my_fieldname2 = %s
					WHERE indexer = %d
					", $my_field2, $some_value);
  $wpdb->query($sql);
If you need to know whether UPDATE was successful
  $Success = $wpdb->query($sql);    //Returns False on Error, otherwise the number of rows affected (will be 0 if you update a row but there were no actual changes of values made)
  if ($Success === False)
    return(False);
  else
    return(True);
If you need to know how many rows were affected
  $Count = $wpdb->query($sql);
  
  if ($Count > 0)
    return(True);
  else
    return(False);

Update From Row + Value Array

/*
  //You can use NOW and NULL with this, e.g.:
    $FieldNamesValuesArray['ColumnName'] = 'NOW';
    $FieldNamesValuesArray['ColumnName'] = 'NULL';

  $FieldNamesValuesArray = array();
  $FieldNamesValuesArray['ColumnName1'] = $ColumnName1;
  $FieldNamesValuesArray['ColumnName2'] = $ColumnName2;
  db_user_write_fields($user_id, $FieldNamesValuesArray);
*/
function db_user_write_fields($user_id, $FieldNameValueArray)
{
  global $wpdb;
  
  $sql = "UPDATE {$wpdb->prefix}tbl_my_table SET ";

  $FirstField = true;
  foreach ($FieldNameValueArray as $key => $value)
  {
    if (!$FirstField)
      $sql .= ",";
    $FirstField = false;
    
    if ($value === 'NOW')
      $sql .= " $key = NOW() ";
    else if ($value === 'NULL')
      $sql .= " $key = NULL ";
    else
      $sql .= $wpdb->prepare(" $key = %s ", $value);
  }
  
  $sql .= $wpdb->prepare(" WHERE user_id = %d", $user_id);

  $wpdb->query($sql);
  
}
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *