Consecutive if statements

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
magicpockets
Forum Newbie
Posts: 2
Joined: Fri Sep 10, 2010 8:35 am

Consecutive if statements

Post by magicpockets »

Hi,

I've just registered as I can't find the answer to what I think is a fairly mundane question through google (other search engines are available) - so first of all hello!

I'm looking at building an error message depending on whether certain fields have been included on submission of a form. In essence it goes like this -

Code: Select all

if (!$_POST['signup_fname']) {
    $displayError = $displayError.'Please enter your first name<br/>';
}
if (!$_POST['signup_lname']) {
    $displayError = $displayError.'Please enter your last name<br/>';
}
if (!$_POST['signup_postcode']) {
    $displayError = $displayError.'Please enter your postcode<br/>';
}
		if (!$_POST['signup_mem_place']) {
			$displayError = $displayError.'Please enter a memorable place<br/>';
		}
I'm sure you can see what I'm trying to achieve - basically if it's true it appends the error message to the existing error message to echo them all when it includes the page to be displayed. Is this a legitimate approach to what I'm trying to achieve? If...else won't work as multiple if statements could be true...

Any help would be appreciated and please bear in mind I've not tested the above code - it's just off the top of my relatively nivoce head to illustrate the point.

Thanks for any help everyone.

MP
User avatar
timWebUK
Forum Contributor
Posts: 239
Joined: Thu Oct 29, 2009 6:48 am
Location: UK

Re: Consecutive if statements

Post by timWebUK »

You could write a reusable function instead to save coding space... for example:

Code: Select all

//Check if $string has been filled - $type being a description
function checkInput($type, $string)
{
	if($string == '')
	{
	echo 'Please enter your '  . $type;
	}
}

//In use...

checkInput($_POST['username'], 'username');
checkInput($_POST['date'], 'date of birth');
checkInput($_POST['email'], 'email address');
Just a small example to get your brain working with the sort of things you could do.
magicpockets
Forum Newbie
Posts: 2
Joined: Fri Sep 10, 2010 8:35 am

Re: Consecutive if statements

Post by magicpockets »

cool, and instead of echo'ing the result, I could append it much in the same way as my example. Thanks for that Tim
Post Reply