I m trying a contact form in php where the details as to get stored in the database.If i dont enter any values it displays error msg but it gets stored in the database. How can I validate form when error message displays the data should not be entered in database. Here is the code
<?php
 $username = "root";
$password = "";
$hostname = "localhost"; 
$db = "abc";
//connection to the database
$name="";
$email="";
$batch="";
$mobile="";
    if (isset($_POST['submit'])) {
    $error = "";
    if (!empty($_POST['name'])) {
    $name = $_POST['name'];
    } else {
    $error .= "You didn't type in your name. <br />";
    }
    if (!empty($_POST['email'])) {
    $email = $_POST['email'];
      if (!preg_match("/^[_a-z0-9]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){ 
      $error .= "The e-mail address you entered is not valid. <br/>";
      }
    } else {
    $error .= "You didn't type in an e-mail address. <br />";
    }
if (!empty($_POST['batch'])) {
    $batch = $_POST['batch'];
    } else {
    $error .= "You didn't type batch. <br />";
    }
     if(($_POST['code']) == $_SESSION['code']) { 
    $code = $_POST['code'];
    } else { 
    $error .= "The captcha code you entered does not match. Please try again. <br />";    
    }
    if (!empty($_POST['mobile'])) {
    $mobile = $_POST['mobile'];
    } else {
    $error .= "You didn't type your Mobile Number. <br />";
    }
    if (empty($error)) {
 $success = "<b>Thank you! Your message has been sent!</b>";
    }
    }
    ?>
              <div id="contactForm">
                <?php
      if (!empty($error)) {
      $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db($db,$dbhandle) or die('cannot select db');
mysql_query("INSERT INTO contact (name,batch,email,mobile) 
                VALUES('$name','$batch','$email','$mobile') ") or die(mysql_error());
      echo '<p class="error"><strong>Your message was NOT sent<br/> The following error(s) returned:</strong><br/>' . $error . '</p>';
      } elseif (!empty($success)) {
      echo $success;
      }
    ?>
 
     
     
     
     
     
    