1

Im working in a php form where Im validating the feilds with regular expression. Validation working fine but I want to insert data into database after the validation finish with no error I dont know how to rite this ?

Im facing a prolem and data is inserting empty records into database each time I click submit. Also , I want after the insert is done to redirect to a Thank you page .

I really appreciate your help and suggestion .

here is my code

<?php
  $errname     = "";
  $errage      = "";
  $errmobile   = "";

  if($_POST["ac"]=="login"){
    // Full Name must be letters, dash and spaces only
      if(preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST["name"]) === 0)
      $errname = '<p class="errText">Please enter your full name </p>';
    // age must be 2 digits
    if(preg_match("/^\d{2}$/", $_POST["age"]) === 0)
      $errage = '<p class="errText">Age must be 2 digits</p>';
              // Mobile mask 050-0000000
    if(preg_match("/^\d{3}-\d{7}$/", $_POST["mobile"]) === 0)
      $errmobile = '<p class="errText">Mobile must be in this format: 050-0000000</p>';


      // contact to database

$connect = mysql_connect("localhost", "root", "") or die ("Error , check your server connection.");

mysql_select_db("career_system");

 //Get data in local variable

$v_name=$_POST['name'];

$v_age=$_POST['age'];

$v_gender=$_POST['gender'];

$v_mobile =$_POST['mobile'];


$query="insert into applicant(name, age, gender, mobile ) values ('$v_name', '$v_age', '$v_gender','$v_mobile ')";

mysql_query($query)  or die(mysql_error());
}
echo "Your information has been received"; 
      }


  ?>

</head>

<body>
<div align="center">
  <p>&nbsp;</p>
</div>
<form name="form1" action="<?php echo $PHP_SELF; ?>" method="POST">
  <p>
    <input type="hidden" name="ac" value="login">
  </p>
  <table width="485" border="0">
      <tr>
        <td width="48">Full Name</td>
        <td width="150"><input name="name" type="text" id="name" value="<?php echo      $_POST["name"]; ?>"></td>
        <td width="273"><?php  if(isset($errname)) echo $errname; ?></td>
      </tr>
      <tr>
        <td>Age</td>
        <td><input name="age" type="text" id="age" value="<?php echo $_POST["age"]; ?>"></td>
        <td><?php  if(isset($errage)) echo $errage; ?></td>
      </tr>
      <tr>
        <td>Gender</td>
        <td><input name="gender" type="radio" value="Male" checked>
          Male 
          <input name="gender" type="radio" value="Female">
          Female</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>Mobile</td>
        <td><input name="mobile" type="text" id="mobile" value="<?php echo $_POST["mobile"]; ?>"></td>
        <td><?php  if(isset($errmobile)) echo $errmobile; ?></td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td><input type="submit" name="Submit" value="Submit">
        <input name="reset" type="reset" id="reset" value="Reset"></td>
        <td>&nbsp;</td>
      </tr>
  </table>
</form>

3 Answers 3

2

You can simply use an $errors array and check for its emptiness before inserting:

$errors = array();

if ($_POST["ac"]=="login") {

    if (!preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST['name']))
        $errors['name'] = '<p class="errText">Please enter your full name </p>';

    if (!preg_match("/^\d{2}$/", $_POST['age']))
        $errors['age'] = '<p class="errText">Age must be 2 digits</p>';

    // etc...

    if (!$errors) {
        $query = "
            insert into applicant 
            (name, age, gender, mobile ) 
            values 
            (
            '".mysql_real_escape_string($v_name)."', 
            '".mysql_real_escape_string($v_age)."', 
            '".mysql_real_escape_string($v_gender)."', 
            '".mysql_real_escape_string($v_mobile)."'
            )
        ";

        mysql_query($query);
    }

    // etc...
}

// Later in your HTML:

<tr>
    <td>Mobile</td>
    <td><input name="mobile" type="text" id="mobile" value="<?php echo $_POST["mobile"]; ?>"></td>
    <td><?php  if(isset($errors['mobile'])) echo $errors['mobile'] ?></td>
</tr>

Make sure to escape data before sending it to the database (hence, the mysql_real_escape_string calls)! An important piece of advice would be to actually abandon the mysql_ functions as they are antiquated. You should use PDO instead. It's much easier, more efficient and eliminates much of the SQL injection threat with little effort:

try {
    $dbh = new PDO("mysql:host=localhost;dbname=mydb", 'username', 'password');
} catch(PDOException $e) {
    die('Could not connect to database!');
}

$stm = $dbh->prepare('INSERT INTO applicant (name, age, gender, mobile ) VALUES (?, ?, ?, ?)');
$stm->execute(array($v_name, $v_age, $v_gender, $v_mobile));
Sign up to request clarification or add additional context in comments.

Comments

1

Add a space after applicant - INSERT INTOapplicant(name, age, gender, mobile )

Also, your code is insecure and your database is now vulnerable to attack. Make sure you escape all of your strings before you insert them into a db!

http://phptutorial.info/?mysql-real-escape-string

Comments

-1

How about something like:

  if($_POST["ac"]=="login"){
    // Full Name must be letters, dash and spaces only
      if(preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST["name"]) === 0)
      $errname = '<p class="errText">Please enter your full name </p>';
    // age must be 2 digits
    if(preg_match("/^\d{2}$/", $_POST["age"]) === 0)
      $errage = '<p class="errText">Age must be 2 digits</p>';
              // Mobile mask 050-0000000
    if(preg_match("/^\d{3}-\d{7}$/", $_POST["mobile"]) === 0)
      $errmobile = '<p class="errText">Mobile must be in this format: 050-0000000</p>';


      // contact to database

$connect = mysql_connect("localhost", "root", "") or die ("Error , check your server connection.");

mysql_select_db("career_system");

 //Get data in local variable

$v_name=$_POST['name'];

$v_age=$_POST['age'];

$v_gender=$_POST['gender'];

$v_mobile =$_POST['mobile'];

if($errname != "" || $errage != "" || $errmobile != "")
   echo "Error!";
else{

$query="insert into applicant(name, age, gender, mobile ) values ('$v_name', '$v_age', '$v_gender','$v_mobile ')";

    mysql_query($query)  or die(mysql_error());
}
}

And just for your own safety, when storing posted values into a database, always check that they are not some type of attack (like for example SQL injection) by using:

mysql_real_escape_string(param);

3 Comments

why connect to the database at all if there are errors in the submitted data?
@ceejayoz: I was not done writing. And the code is a copy of his code as a solution to his problem.
Submitted as a alternative solution, after I submitted I registered that his code is vulnerable to attacks, so I edited it. At the same time you gave me the comment...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.