Jump to content

Form validation and info to table


Johnnyboy123

Recommended Posts

Think I made a post about this earlier but doesn't show so dont think it posted successfully but if it did, my bad haha. Basicly I have a form which sends info to my database table after submitted. I added some form validation so when the user didn't enter a required field, text appears stating that the field needs to be entered. However, whether the field is entered or not, if the user submits the info still goes to the database. How do I fix it so that it only sends the info to the database once the required fields are entered? Do I go about it with an if statement?

 

Heres my code up until now:

 

<?php
if (isset($_POST['submit'])) {

	// forms inputs set to variables



$cname = mysql_real_escape_string($_POST['cname']);
$sname = mysql_real_escape_string($_POST['sname']); 
$init = mysql_real_escape_string($_POST['init']); 
$fname = mysql_real_escape_string($_POST['fname']); 
$title = mysql_real_escape_string($_POST['title']); 
$msname = mysql_real_escape_string($_POST['msname']); 
$dob = mysql_real_escape_string($_POST['dob']); 
$sex = mysql_real_escape_string($_POST['sex']);  
$lang = mysql_real_escape_string($_POST['lang']); 
$idno = mysql_real_escape_string($_POST['idno']); 
$telh = mysql_real_escape_string($_POST['telh']); 
$telw = mysql_real_escape_string($_POST['telw']); 
$cell = mysql_real_escape_string($_POST['cel']); 
$fax = mysql_real_escape_string($_POST['fax']); 
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']); 

$errorstring =""; //default value of error string


if (!$sname)
	$errorstring = $errorstring . "Surname<br>";

if (!$fname)
	$errorstring = $errorstring . "First name<br>";

if (!$title)
	$errorstring = $errorstring . "title<br>";

if (!$dob)
	$errorstring = $errorstring . "date of birth<br>";

if (!$sex)
	$errorstring = $errorstring . "sex<br>";

if (!$idno)
	$errorstring = $errorstring . "id number<br>";

if (!$email)
	$errorstring = $errorstring . "email address<br>";

if (!$address)
	$errorstring = $errorstring . "address<br>";


if ($errorstring!="")
	echo "Please fill out the following fields:<br>$errorstring";

else
{
//run code
die("success!");
}



	// query
$sql = "INSERT INTO student (sno, cname, sname, init, fname,
						title, msname, dob, sex, lang, idno,
						telh, telw, cel, fax, email, address
						)

	VALUES 				('', '$cname', '$sname', '$init', '$fname', 
						'$title', '$msname', '$dob', '$sex','$lang',
						'$idno', '$telh', '$telw', '$$cell', '$fax',
						'$email', '$address')";


          mysql_query($sql) or die('Error:' . mysql_error()); 
	  
	  

	  



}
mysql_close($link); 

?>

 

It's a project, first time I'm attempting form validation so this is rather new for me. With that being said, please feel free to give any tips and criticism as this is a learning curve for me. Also I'm probably going to add some security later for sql injection etc. so if anyone has some tips on that it would be great. Almost done with that damn project, thanks in advance :)

Link to comment
Share on other sites

Looks like you need to bracket you statement.

if ($errorstring!=""){
	echo "Please fill out the following fields:<br>$errorstring";
}	
else
{
$sql = "INSERT INTO student (sno, cname, sname, init, fname,
						title, msname, dob, sex, lang, idno,
						telh, telw, cel, fax, email, address
						)

	VALUES 				('', '$cname', '$sname', '$init', '$fname', 
						'$title', '$msname', '$dob', '$sex','$lang',
						'$idno', '$telh', '$telw', '$$cell', '$fax',
						'$email', '$address')";


          mysql_query($sql) or die('Error:' . mysql_error());
}

Link to comment
Share on other sites

also, i would change your form validation if statements to elseif statements

if (!$sname)
	$errorstring = $errorstring . "Surname<br>";

elseif (!$fname)
	$errorstring = $errorstring . "First name<br>";

elseif (!$title)
	$errorstring = $errorstring . "title<br>";

elseif (!$dob)
	$errorstring = $errorstring . "date of birth<br>";

in this case it wont make a huge difference, however its a good practice to get in to

Link to comment
Share on other sites

You shouldn't use elseif logic when validating different form fields because only the first test to fail will be reported. You will piss off your visitors if they have to repeatedly submit the form, once for each validation problem. You want to validate and report all the independent problems at once.

 

The only time you would use elseif logic when validating form data is when you are performing related tests on one value and you want the validation to stop on the first error, such as first checking if a value is empty, followed by checking if the value is too short. If it is empty, you don't want to display that it is was also too short.

Link to comment
Share on other sites

Ah ok makes sense. Will keep that in mind. How do I go about setting restrictions on the data that has to be entered. I already made it so the field can't be left blank. Say for instance, one of the number fields i.e date of birth, how do I restrict that field so the user can only submit numbers and only a limited amount?

Link to comment
Share on other sites

Ah nevermind figured out how to restrict the number of characters limit and to numbers. But say for instance I have a field such as home tel nr which requires the nr code + nr. So it will have to have characters + numbers e.g (+27 or whatever) for code and then 9405690 for the home nr. How do I restrict it to that?  I currently just went with if (!is_numeric($dob)) for numbers.

Link to comment
Share on other sites

Ah nevermind figured out how to restrict the number of characters limit and to numbers. But say for instance I have a field such as home tel nr which requires the nr code + nr. So it will have to have characters + numbers e.g (+27 or whatever) for code and then 9405690 for the home nr. How do I restrict it to that?  I currently just went with if (!is_numeric($dob)) for numbers.

 

Typically people will use regular expressions to deal with complex pattern matching.

Link to comment
Share on other sites

  • 2 weeks later...

hi Johnnyboy123 i am having that same thing happening to me i have been working on it for over 3 weeks now, could i ask if i can see all of your code and page names. pleas it would help me to see how it all linked, and might make it click in my brain.  please please thanks.

Link to comment
Share on other sites

hi all i am new to the site and i to am having the same problem that Johnnyboy123 is having ii have looked all over the net for 3 weeks now and cant find any thing at all i need some ones help pleas and fast. here is all of my code..

Basicly I have a form which sends info to my database table after submitted. I added some form validation so when the user didn't enter a required field, text appears stating that the field needs to be entered. However, whether the field is entered or not, if the user submits the info still goes to the database. How do I fix it so that it only sends the info to the database once the required fields are entered? Do I go about it with an if statement?

Demo.php

 

<?php

session_start();

 

if(!isset($_REQUEST['Hompage'])){

echo "<center>Your information has been sent please click on the link to take you back to the Homepage.</center><br />";

echo "<center><a href=index3dart.php>Home.";

 

 

}

define('DB_NAME', 'Eclipse_media');

define('DB_USER', 'root');

define('DB_PASSWORD', 'Steph1989');

define('DB_HOST', 'localhost');

 

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

 

if (!$link) {

die('Could not connect: ' . mysql_error());

}

 

$db_selected = mysql_select_db(DB_NAME, $link);

 

if (!$db_selected) {

die('Can\'t use ' . DB_NAME . ': ' . mysql_error());

}

 

$value = $_POST['company_name'];

$value2 = $_POST['contact_name'];

$value3 = $_POST['address'];

$value4 = $_POST['street_number'];

$value5 = $_POST['postcode'];

$value6 = $_POST['contact_number'];

$value7 = $_POST['contact_email'];

$value8 = $_POST['budget'];

$value9 = $_POST['description'];

 

$sql = "INSERT INTO 3dartactforms (company_name, contact_name, address, street_number, postcode, contact_number, contact_email, budget, description) VALUES ('$value', '$value2', '$value3', '$value4', '$value5', '$value6', '$value7', '$value8', '$value9')";

 

if (!mysql_query($sql)) {

die('Error: ' . mysql_error());

}

 

mysql_close();

 

?>

 

 

form.php

 

 

<?php

error_reporting(0);

 

$errors = array(); // set the errors array to empty, by default

$fields = array(); // stores the field values

$success_message = "";

 

if (isset($_POST['submit']))

{

  // import the validation library

  require("validation.php");

 

  $rules = array(); // stores the validation rules

 

  // standard form fields

  $rules[] = "required,company_name,Company Name is required.";

  $rules[] = "required,contact_name,Contact Name is required.";

  $rules[] = "required,contact_email,Please enter your email address.";

  $rules[] = "valid_email,email,Please enter a valid email address.";

  $rules[] = "required,street_number,Street Number is required.";

  $rules[] = "required,address,Address is required.";

  $rules[] = "required,postcode,Postcode is required.";

    $rules[] = "required,contact_number,Contact Number is required.";

  $rules[] = "required,budget,Budget is required.";

  $rules[] = "required,description,Description is required.";

 

 

  $errors = validateFields($_POST, $rules);

 

  // if there were errors, re-populate the form fields

  if (!empty($errors))

  { 

    $fields = $_POST;

  }

 

  // no errors! redirect the user to the thankyou page (or whatever)

  else

  {

    $message = "All fields have been validated successfully!";

   

    // here you would either email the form contents to someone or store it in a database.

    // To redirect to a "thankyou" page, you'd just do this:

    // header("Location: thanks.php");

  }

}

 

 

 

         

?>

<style type="text/css">

<!--

body,p,table,td,input,select {

  font-family: verdana, tahoma;

font-size: 8pt;

  line-height: 14pt;

}

.demoTable {

  background-color: #efefef;

  width: 100%;

}

.title { font-family: arial; font-size: 16pt; }

.section { font-size: 11pt; color: #3366cc; }

.error {

  border: 1px solid red;

  background-color: #ffffee;

  color: #660000;

  width: 400px;

  padding: 5px;

}

.notify {

  border: 1px solid #336699;

  background-color: #ffffee;

  color: #336699;

  width: 400px;

  padding: 5px;

}

-->

</style>

 

 

<table cellspacing="0" width="600" align="center">

<tr>

  <td>

   

    <form action="<?=$_SERVER['PHP_SELF']?>" method="post">

   

   

    <?php

   

    // if $errors is not empty, the form must have failed one or more validation

    // tests. Loop through each and display them on the page for the user

    if (!empty($errors))

    {

      echo "<div class='error' style='width:100%;'>Please fix the following errors:\n<ul>";

      foreach ($errors as $error)

        echo "<li>$error</li>\n";

   

      echo "</ul></div>";

    }

   

    if (!empty($message))

    {

      echo "<div class='notify'>$success_message</div>";

    }

    ?>

 

<p>3D Graphics ACT</p>

 

<form class="cmxform" id="signupForm" method="post" action="">

<fieldset>

    <p>

<label for="firstname">Company Name:</label>

<input id="company_name" name="company_name" />

</p>

<p>

<p>

<label for="lastname">Contact Name:</label>

<input id="contact_name" name="contact_name" />

</p>

<p>

<p>

<label for="email">Email</label>

<input id="email" name="contact_email" />

</p>

<p>

<p>

<label for="streetnumber">Street Number:</label>

<input id="street_number" name="street_number" />

</p>

        <p>

<p>

<label for="address">Address:</label>

<input id="address" name="address" />

</p>

  <p>

  <p>

<label for="postcode">Postcode:</label>

<input id="postcode" name="postcode" />

</p>

          <p>

  <p>

<label for="contact_number">Contact Number:</label>

<input id="contact_number" name="contact_number" />

</p>

         

          <p>

  <p>

<label for="budget">Budget:</label>

<input id="budget" name="budget" />

</p>

       

Description: <textarea rows="10" cols="40" name="description"></textarea></p>

<p>

    <p>

<p>

<input type="submit" name="submit" value="SUBMIT" /></p>

   

    </form>

 

 

 

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.