Step 1: Client Side Validation
You will need to do a little more than this to ensure fields are not empty. I would suggest starting with client-side validation using JavaScript. There area number of scripts and tutorials out there for this, I would recommend either of these two:
This will help ensure that if a user submits the form that they will be forced to fill in all form fields before the data will be sent to the server.
Step 2: Server Side Validation
If you are trying to accomplish a blanket check of form values within a form I'd do something like this:
$form_fields = array('email','fname','lname');
$isValid = true;
foreach($_POST as $key=>$value){
if(in_array($key,$form_fields)){
if(empty($value) {
$isValid = false;
}
}
}
if(!isValid) {
header("Location: /add.php?error=1");
die();
}
With this approach you're defining all of the field names you care about at the top of the script and just running through the $_POST object to see if there is data/value assigned. This does not, of course, take into account any validation on the type of data coming in through and I would recommend considering doing this so that you're not getting bad data. If you need to check for improperly formatted data then you will have to check each form input individually.
Step 3: Prepared SQL Statements
The last recommendation to protect against SQL injections would be to use prepared SQL statements when inserting data into the database. Or to consider an ORM that does this for you. For this I would recommend:
Optional Step: PHP Nonce
If you're worried that someone will submit SPAM through the page that processes your form, one thing you can do is implement a nonce. This cryptographic key will ensure that a form can only be submitted once, and any other submissions will be rejected. Again, I'm not sure how secure you want to be with your project but this is also something to consider.
This is a pretty good library for nonces in PHP:
if (!$_POST['submit']) {toif (!isset($_POST['submit'])){it's the simplest method.