Jump to content

[SOLVED] "Break" an IF Statement


hanlonj

Recommended Posts

Hi,

 

I have an html form and a lot of form validation in my processing script. I use many "if" statements before I get to the part of the script where the form contents are emailed to a company.

 

Here is my question, my script validates all fields in the form but if it finds an error it notifies the user to try again, however, the program continues to execute down to the "mail()" function no matter what errors are on the form. I have tried to use "break;" at the end of each "if" statement but it won't work.

 

Any suggestions on how to stop the program if my error checking traps an error?

 

stoney

Link to comment
https://forums.phpfreaks.com/topic/56781-solved-break-an-if-statement/
Share on other sites

die(); would work easily, but if you put it all together and leave the mail function at the end it would work:

 

<?php

$var = $_POST['var'];

if($var){

if(strlen($var) > 32){
echo "error";
}else {
	if(!ctype_alnum($var)){
	echo "error";
	}else {
		//send mail
	}
}
}else {
echo "var not defined";
}

?>

Do something like this:

 

<?php

if (empty($var) || $var <2){ //This is just an example of your error checking
   echo "Error checking found something wrong, please fix the error";

} else {
   //put your mail script here
}

?>

 

The key to that code is the ELSE statment, if it finds errors it won't execute the mailing part.

 

Your other option would be exiting the rest of the script if the statement did find errors.

 

To do that, you would just put this at the end of your if statement that checks for errors.

exit;

 

Although that will exit everything below that....so if you have footers, they will not be shown. so the first way might be the better method in your case.

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.