/*
      $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 tbl_my_table SET ";

  $Values = array();
  $Types = "";
  $FirstField = True;
  foreach ($FieldNameValueArray as $key => $value)
  {
    if ($FirstField)
      $sql .= " $key = ? ";
    else
      $sql .= ", $key = ? ";
    $FirstField = False;
    
    $Values[] = $value;
    $Types .= "s";    //Mark all types a string as MySql will happily accept numeric values as a string also
  }
  
  $sql .= " WHERE user_id = ? ";
  $Values[] = $user_id;
  $Types .= "s"; 

  $stmt = $maindb->prepare("$sql");
  $stmt->bind_param($Types, ...$Values);      //"..." is an argument unpacking operator, its converts the array into individual variables required by bind_param()
  $stmt->execute();
  
}
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 *