Validate and process form before sending to database

Hi all,

I’ve done this before but for the life of me can’t remember how i did it or find the script (it was at least 5yrs ago and I’ve hardly touched code since then). I currently have the validation and database insertion on the same page - on a different page from the form. They both work separately with no problems but the only problem I have is that when I enter something that isn’t correct it displays the error but the script doesn’t stop it from sending data to the database. I was just wondering what I need to do to ensure that this happens?

Newbie…for the 2nd time :smiley:


$error = array();

if($_POST['foo']) == '' )
    $error[] = 'Foo can not be empty';
}

if(empty($error)) {
    $db->query(INSERT...);
}

thanks for that. I’m away on work at the moment but would I be right to assume that as I have multiple fields in the form I would just continue on using the elseif statement?

I wouldn’t. If you want to print all the errors just use a foreach loop

foreach($errors as $error) {
    echo $error;
}

I use a foreach loop in my messages function which prints out errors, warnings, success messages, etc., and then just put that in my page in my <header> and then process all PHP before the header, so that if something goes wrong it will print in the messages function.

Doing it this way ensures that nothing important happens if an error is set, because you’re only performing important actions when the $error array is empty. I set the $error array in my config file so it’s empty on every page load.

Of course, this is an overly simple example. I check for $error, $success, and $warning in my messages function and print out accordingly. I can also use the key in the error array to pass special messages to my form class so that each field will have a customized message printed next to it. It’s pretty flexible doing it this way. :slight_smile:

$error = array();

function messages() {
	global $error;
	if(!empty($error)) {
		foreach($error as $err) {
			$return .= $err;
		}
		return $return;
	} else {
		return false;
	}
}

if($_POST['foo']) == '' ) 
    $error[] = 'Foo can not be empty'; 
} 

if(empty($error)) { 
    $db->query("INSERT..."); 
}


echo messages();