Jump to content

Is there a way of combing functions into one smaller function


AdRock

Recommended Posts

I have several functions for a form that will either repopulate the text fields with the original values from the database if validation fails or if validation passes leave the new values in there.

 

These functions are all the same apart from the variables held in each.

 

Is there a way i can use one function for each of the form text fields which variables change.

 

I thought of maybe using a switch statement or maybe a some sort of loop that uses foreach but i have never used that so don't know how i would go about doing it.

 

Has anyone got any suggestions?

 

Here is the code i have got

if(isset($_POST['submit']))
{
             $submit = $_POST['submit'];
}

$result = mysql_query("SELECT `first_name`, `last_name`, `username`, `email` FROM `users` WHERE `username`='".$_SESSION['username']."'");
while($row = mysql_fetch_assoc($result))
{
    $get_first_name = $row['first_name'];
    $get_last_name = $row['last_name'];
    $get_username = $row['username'];
    $get_email = $row['email'];
}

function error_username($error) {
    global $get_username, $username_print_again, $username;

    //if the new username has got an error, display the original username 
    if($error['username']) { 
        echo $get_username; 
    }
    elseif(($get_username != $username) && ($username != null)) {
	echo $username;	
    }
    else
    {
                if(!$username_print_again) {
            echo $get_username;
    		}
    }
	}

function error_firstname($error) {
    global $get_first_name, $first_name_print_again, $first_name;

    //if the new username has got an error, display the original username 
    if($error['first_name']) { 
        echo $get_first_name; 
    }
    elseif(($get_first_name != $first_name) && ($first_name != null)) {
	echo $first_name;	
    }
    else
    {
                if(!$first_name_print_again) {
            echo $get_first_name;
    		}
    }
}

function error_lastname($error) {
    global $get_last_name, $last_name, $last_name_print_again;

    //if the new username has got an error, display the original username 
    if($error['last_name']) { 
        echo $get_last_name; 
    }
    elseif(($get_last_name != $last_name) && ($last_name != null)) {
	echo $last_name;	
    }
    else
    {
                if(!$last_name_print_again) {
            echo $get_last_name;
    		}
    }
	}

 

If you need to see any more code i'll post it

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.