Take the 2-minute tour ×

On my website, I have user accounts that are configurable with forms that allow users to update everything from first and last names to privacy settings. I use the following function to update the database with that input. (Note that the following code uses WordPress-specific features.)

function update_account() {
    global $current_user; get_currentuserinfo();
    require_once( ABSPATH . WPINC . '/registration.php' );

    $uid = $current_user->ID;

    // First Name
    if(isset($_POST['first_name']) && $_POST['first_name'] <> $current_user->first_name) {
        wp_update_user( array( 
            'ID' => $uid, 'first_name' => esc_attr($_POST['first_name'])

    // ...and so on 43 more times...


This feels like the wrong way to process forms. This also looks like it will negatively impact server performance when there are multiple users and frequent updates, given that the if-then-else conditions for every field, even fields not on a particular page, force checking each field for input.

Moreover, since form data can be expected to remain relatively constant, I added the <> operator to prevent the function from updating fields where there has not been any change, but I suspect this also means that every field is still evaluated for change. To make matters worse, adding new fields -- there are already 44 fields in total -- is an unwieldy process.

What's a better way to process form data?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

Keep an array of the fields you will be processing with this code, and iterate over it. This works if all your attributes are strings, for example. If you have different data types such as boolean flags to handle differently from the strings, you may wish to group them into their own array.

// All the fields you wish to process are in this array
$fields = array('first_name', 'last_name', 'others',...'others99');

// Loop over the array and process each field with the same block
foreach ($fields as $field) {
    if(isset($_POST[$field]) && $_POST[$field] != $current_user->{$field}) {
        wp_update_user( array( 
            'ID' => $uid, $field => esc_attr($_POST[$field])
share|improve this answer
Oh, that's interesting. I could even generate the array from the database to skip messing with the source. Doesn't this iterate over every field though, even nonrelevant fields? Can there be a significant impact on CPU or memory with a large array? –  fireundubh Nov 1 '11 at 2:27
@fireundubh It only iterates over fields you've defined in the array. But if they aren't set in $_POST, they will be skipped in the loop, the same as you have already done with your 44 if() statements. I wouldn't worry about the performance of it until you actually find it to be problematic, then tune it. –  Michael Berkowski Nov 1 '11 at 2:30
Why not reverse it and check the in_array($key), with foreach ($_POST as $key => $val)? –  Jared Farrish Nov 1 '11 at 2:31
I adapted your solution and retrieved the field key-value pairs from the database. There are some security-related SQL issues to work out, but that's a different question. Thank you. –  fireundubh Nov 1 '11 at 9:15

There's a lot of things missing with your implementation. I don't know what kinds of data you're allowing the user to manipulate but most usually have some kind of requirements to be acceptable. Like not having certain characters, not being blank, etc. I don't see any validation occurring, so how do you handle values that might be undesirable? And what happens when you receive bad data? How do you inform the user of the bad data and prompt them to correct it?

If we abstract the situation a bit we can come up with generalizations and implement an appropriate solution. Basically form fields [can] have a default value, a user specified value [on form review], validation requirements and validation errors [with messages]. A form is a collection of fields that upon form submit needs to be validated and if invalid, re-displayed to the user with instructive corrective prompts.

If we create a form class that encapsulates the above logic we can instantiate and use it to pass around our controller/views. Oops, I was just assuming you were using an Model/View/Controller type framework, and I'm not really familiar with wordPress so I don't know if that is exactly applicable. But the principle still applies. On the page where you both display or process the form, here's some pseudo logic how how it might look.

function update_account()
    // initialize a new form class
    $form = new UserAccountInfoForm();
    // give the form to your view for rendering 
    $this->view->form = $form;
    // check if form was posted [however your framework provides this check]
        return $this->render('accountform.phtml');
    // check if posted form data validates
         // if the form didn't validate re-display the form
         // the view takes care of displaying errors, with the help of its
         // copy of the $form object
         return $this->render('accountform.phtml');

    // form validated, so we can use the supplied values and update the db
    $values = $form->getValues(); // returns an array of ['fieldname'=>'value']
    // escape the values of the array
    // update db
    // inform the user of successful update via flash message
    $this->flashMessage('Successfully updated profile');
    // go back to main profile page

That makes your controller relatively clean an easy to work with. The view gets some love and care to, utilizing the $form value to display the form correctly. Technically, you can implement a method in the form class to give you the form html, but for simplicity I'm just going to assume your form html is manually coded in accountform.phtml and it just uses $form to get field info

<form action='post'>
<label>first name</label> <input class='<?=$this->form->getElement('first_name')->hasError() ? "invalid":""?>' type='text' name='first_name' value="<?=$this->form->getElement('first_name')->getValue()"/> <span class='errmsg'><?=$this->form->getElement('first_name')->getError()?></span><br/>

<label>last name</label> <input class='<?=$this->form->getElement('last_name')->hasError() ? "invalid":""?>' type='text' name='last_name' value="<?=$this->form->getElement('last_name')->getValue()"/> <span class='errmsg'><?=$this->form->getElement('last_name')->getError()?></span><br/>

<label>other</label> <input class='<?=$this->form->getElement('other')->hasError() ? "invalid":""?>' type='text' name='other' value="<?=$this->form->getElement('other')->getValue()"/> <span class='errmsg'><?=$this->form->getElement('other')->getError()?></span><br/>


Here the pseudo code relies on the form class method "getElement" which returns the field class instance for the specified field name (which would be created an initialized in the constructor of your form class). Then on the field class methods "hasError" and "getError" to check if the field validated correctly. If the form has not be submitted yet, then these return false and blank, but if the form was posted and invalid, then they will have been set appropriately in the validate method when it was called. Also "getValue" would return either the value supplied by the user when the form was submitted, or if the form has not been submitted, the default value as specified when the field class was instantiated and initialized.

Obviously this pseudo code is relying on a lot of magic that you'd have to implement if you roll your own solution--and it's certainly doable. However, at this point I'll direct you to the Zend Framework Zend_Form components. You can use zend framework components by themselves without having to utilize the entire framework and application structure too. You might also find similar form component solutions from other frameworks but I wouldn't know about those (we are a Zend Framework shop at my work place).

Hopefully this hasn't been too complicated, and you know where to go from here. Of course just ask if you need any clarification.

share|improve this answer

Your Answer


