Prevent blank or improperly formatted data from inserting to database

Hello, I am new to PHP and MySQL. I have the below php code inside my web form and I am having a problem with it inserting a new record to the database when any of the web fields are blank or improperly formatted.

I have error checking occuring that will display an error message in red after pressing Submit button AND data is either blank or improperly formatted. This part is working fine, the problem is that it still allows the record to post to the database when there are blank/improperly formatted values. I would like to add some scripting to check to see if any of the mandatory fields are blank or formatted improperly and if so, do not proceed with the SQL Insert. I would appreciate if someone can help me with what scripting I should add. Below is the code I am using, thanks!

<!DOCTYPE HTML>  
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>  

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["Name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["Name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $nameErr = "Only letters and white space allowed"; 
    }
  }
  
  if (empty($_POST["Email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["Email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
    }
  }
    
  if (empty($_POST["Website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["Website"]);
    // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
      $websiteErr = "Invalid URL"; 
    }
  }

  if (empty($_POST["Comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["Comment"]);
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }

if (empty($_POST["Subscription"])) {
    $subErr = "Subscription is required"; }
 else {
    $sub = test_input($_POST["Subscription"]);
    }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>

<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
    <p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
 <legend>Newspaper Subscription Request</legend>  
  Name: <input type="text" name="Name" value="<?php echo $name;?>">
  <span class="error">* <?php echo $nameErr;?></span>
  <br><br>
  E-mail: <input type="text" name="Email" value="<?php echo $email;?>">
  <span class="error">* <?php echo $emailErr;?></span>
  <br><br>
  Website: <input type="text" name="Website" value="<?php echo $website;?>">
  <span class="error"><?php echo $websiteErr;?></span>
  <br><br>
  Comment: <textarea name="Comment" rows="5" cols="40"><?php echo $comment;?></textarea>
  <br><br>
  Gender:
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
  <span class="error">* <?php echo $genderErr;?></span>
    <br><br>
  Subscription:
   <select name="Subscription">
       <option value=""></option>
   <option value="Daily">Daily</option>
   <option value="Evening">Evening</option>
   <option value="Weekly">Weekly</option>
   <option value="Monthly">Monthly</option>
</select> 
  <span class="error">* <?php echo $subErr;?></span>

  <br><br>
  <input type="submit" name="submit" value="Submit"> 
<br><br>
<a href="https://www.google.com/">Visit Admin Page</a>
 </fieldset>
</form>



<?php

 if (isset($_POST['submitted'])) {

	include('connect-mysql.php');


         
$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO subscriptions (Name, Email, Comment, Subscription) VALUES ('$fname',
'$femail', '$fcomment', '$fsubsciption')";

      if (!mysqli_query($dbcon, $sqlinsert))  {
           die(mysqli_error($dbcon)); // and die('error inserting new record'); ;       

  }     // end of nested if statement

  // else
        $newrecord = "1 record added to the database";

}  // end of main if statement

?>

<?php

echo $newrecord

?>



</body>
</html>

If either of these conditions are met, you don’t want to continue and submit the data, but rather you want to redirect back to the form so the user can correct his errors. If you use header('Location: form.php') to redirect (replace form.php with whatever file your form is in), you have to make sure that your php code is at the very top of the page, or you will get an error. You have to have the header('Location: ...') before any output on the page (including whitespace).

if ($_SERVER["REQUEST_METHOD"] == "POST") {

   if (empty($_POST["Name"])) {
    $nameErr = "Name is required";

   // REDIRECT HERE

  } else {

    $name = test_input($_POST["Name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $nameErr = "Only letters and white space allowed"; 

     // REDIRECT HERE

    }
   
  }

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.