Hey,
I am going throguh a list of variables and making PHP validate each one using an if statement. How can I make PHP sort of stop and end the script if it comes accross an invalid variable?
Well say you have a function doing this, simply use the return command:
function validate(){
if(){
return false;
}
}
Any code after that is ignored.
If you want to completely stop the script, use the exit command:
exit;
If I have a line like this when a validation fails:
$error_detail = "Cost is invalid";
How can I add another text string to that when another validation fails?
Is it as simple as writing something like:
$error_detail = $error_detail."Name is invalid";
You’d be better off with an array.
$Errors = array();
if(cost_is_invalid){
$Errors[] = 'Cost is invalid';
}
if(name_is_invalid){
$Errors[] = 'Name is invalid';
}
//....
if(empty($Errors)){
//success
}else{
//fail
}
Better use array to store multiple error messages:
$error = array();
if(empty($name)){
$error[] = 'Name is blank.';
}
if(empty($email)){
$error[] = 'Email is blank.';
}
Now you can store it in the session or handle in some ways to report the error messages in the page.
I have just tried:
if (!empty($errors)) {
echo "<ul>";
foreach($errors as $error) {
echo "<li>".$error."</li>";
}
echo "</ul>";
} else {
but it says theres an error and I think it’s to do with the “!” but not quite sure how?
What’s the error? Nothing wrong with that except the else isn’t closed.
I have no idea why I got an error but I managed to fix it.
Thanks