I'm sure the initial reaction is going to be something like, "Doesn't this guy have Google?" Yes, I'll admit this does seem like a pretty basic concept and I've tried and tried to wrap my head around it, looked up all manner of posts and articles on the topic, etc., but all to no avail. Perhaps you can point me in the right direction?
I have a basic contact form (contact.html) that I run with an external PHP script (contact.php). Here's the HTML form code:
<form id="form1" action="contact.php" method="post">
<div class="form1">
<label>Your Name:</label>
<span><input type="text" name="name" /></span>
</div>
<div class="form1">
<label>Your School:</label>
<span><input type="text" name="school" /></span>
</div>
<div class="form1">
<label>Phone Number:</label>
<span><input type="text" name="phone" /></span>
</div>
<div class="form1">
<label>E-Mail Address:</label>
<span><input type="text" name="email" /></span>
</div>
<div class="form3">
<span><textarea cols="1" rows="1" name="message"></textarea></span>
</div>
<div class="wrapper">
<input class="submit" type="image" src="images/contact_submit.png" name="submit" alt="Submit" />
</div>
</form>
The PHP script validates that all of the fields were entered and then processes the form:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//Validate the name:
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
echo "You forgot to enter your name.<br>";
}
//Validate the school:
if (!empty($_POST['school'])) {
$school = $_POST['school'];
} else {
echo "You forgot to enter your school.<br>";
}
//Validate the e-mail:
if (!empty($_POST['email'])) {
$email = $_POST['email'];
} else {
echo "You forgot to enter your e-mail.<br>";
}
//Validate the message:
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
echo "You forgot to enter a message.";
}
if (!empty($_POST['name']) && !empty($_POST['school']) && !empty($_POST['email']) && !empty($_POST['message'])) {
$phone = $_POST['phone'];
$body = "$name\n$school\n$phone\n$email\n\n$message";
mail("***", "PAL Website - Message from a Visitor", $body);
header("Location: confirm.html");
}
}
?>
Everything works great and the form is validated and processed as intended. However, I REALLY want to set it up so that the error messages are displayed on the same page or at least have the form refreshed with the error messages included.
I've seen this done in other demonstrations (Larry Ullman's book, for example), but still can't quite figure out how to make it happen. Can you please offer advice? What's the simplest way to go about it?
Here's the page URL, if it helps: http://www.712jefferson.org/pal/contact.html
Thank you!
I'd use jQuery for this.
Modifications to be made:
in HTML:
add id to your input fileds, so you can "grab" them with jQuery (You can see the usage in the $.post method below).
<form id="form1" action="contact.php" method="post">
<div class="form1">
<label>Your Name:</label>
<span><input id="name" type="text" name="name" /></span>
</div>
<div class="form1">
<label>Your School:</label>
<span><input id="school" type="text" name="school" /></span>
</div>
<div class="form1">
<label>Phone Number:</label>
<span><input id="phone" type="text" name="phone" /></span>
</div>
<div class="form1">
<label>E-Mail Address:</label>
<span><input id="email" type="text" name="email" /></span>
</div>
<div class="form3">
<span><textarea id="message" cols="1" rows="1" name="message"></textarea></span>
</div>
<div class="wrapper">
<input class="submit" type="image" src="images/contact_submit.png" name="submit" alt="Submit" />
</div>
</form>
in PHP:
if there is no error in validation echo this: "success"
if (!empty($_POST['name']) && !empty($_POST['school']) && !empty($_POST['email']) && !empty($_POST['message'])) {
echo "success";
$phone = $_POST['phone'];
$body = "$name\n$school\n$phone\n$email\n\n$message";
mail("***", "PAL Website - Message from a Visitor", $body);
header("Location: confirm.html");
}
Attach jQuery library to your site and use the code below in your HTML file inside brackets or in an external *.js file attached to Your site.
In Your HTML file's section use this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
jQuery script:
$('#form1').submit(function() {
event.preventDefault();
$.post("contact.php", {name: $("#name").val(), school: $("#school").val(), phone: $("#phone").val(), email: $("#email").val(), message: $("#message").val()}, function(data){
if(data !="success"){
alert(data);
}
});
});
This will give Your error messages in a alert window and Your site won't reload if I'm not mistaken.
There are many ways of doing this so this is a opinion based question which will get you several ways of accomplishing this.
You could do an ajax request to submit the data that way no reloading of the page and on the success of the call if any errors are in the response show the errors near the input that caused the error. This would require the use of javascript and setting a hidden element to the error and displaying it or generating the element containing the error and appending it to the DOM.
do as Amal Murali shows and put the html and validation script in the same script file and output the errors right away, or even better echo the errors near the inputs that caused them
yet another way would be to have contact.php do the validation and then on invalid data print out contact.html and again put the errors near the inputs.
<?php
// define variables and set to empty values
$firstnameErr = $lastnameErr = $usernameErr = $passwordErr = $genderErr = $courseErr = "";
$firstname = $lastname = $username = $password = $gender = $comments = "";
$course = array();
//var_dump($_POST['gender']);
//exit;
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$variables = array();
$variables = initialize();
$errors = array();
$errors = validate_errors($variables);
if (count($errors) == 0) {
//database operation
//exit;
}
}
function clean($data) {
$data = strip_tags(htmlspecialchars(stripslashes(trim($data))));
//trim :- Strip whitespace (or other characters) from the beginning and end of a string
//The stripslashes() function removes backslashes.Prevents XSS
//htmlspecialchars :- Converts the predefined characters "<" (less than) and ">" (greater than) to HTML entities:< (less than) becomes < and > (greater than) becomes >Helps in preventing XSS
//The strip_tags() function strips a string from HTML, XML, and PHP tags.
return $data;
}
function initialize(){
$var = array();
$var['firstname'] = clean($_POST['firstname']);
$var['lastname'] = clean($_POST['lastname']);
$var['username'] = clean($_POST['username']);
$var['password'] = clean($_POST['password']);
if(!empty($_POST['gender'])) { //if-else condition is used because here we don't type in any data,but just select data
$var['gender'] = $_POST['gender'];
} else {
$var['gender'] = '';
}
//var_dump($_POST[gender]);
if(!empty($_POST['course'])) { //if-else condition is used because here we don't type in any data,but just select data
$var['course'] = $_POST['course'];
} else {
$var['course'] = '';
}
$var['comments'] = clean($_POST['comments']);
return $var;
}
function validate_errors($var) { //is an array being passed into this function??have a look at arg of validateFirstName.
$errors = array();
$errors['firstname'] = validateFirstName($var['firstname']);//should return error string or ''
$errors['lastname'] = validateLastname($var['lastname']);
$errors['username'] = validateUserName($var['username']);
$errors['password'] = validatePassword($var['password']);
$errors['gender'] = validateGender($var['gender']);
$errors['course'] = validateCourse($var['course']);
$errors['comments'] = validateComments($var['comments']);
return $errors;
}
function validateFirstName($fname){
if(empty($fname)){
global $firstnameErr;
$firstnameErr = "First name is required";
return $firstnameErr;
} else if (!preg_match("/^[a-zA-Z ]*$/", $fname)){ // check if name only contains letters and whitespace.Performs a regular expression match
global $firstnameErr;
$firstnameErr = "Only letters are allowed";
return $firstnameErr;
} else {
global $firstname;
$firstname = $fname;
return '';
}
}
function validateLastName($lname){
if(empty($lname)){
return '';
} else if (!preg_match("/^[a-zA-Z ]*$/", $lname)) { // check if name only contains letters and whitespace,performs a regular expression match
global $lastnameErr;
$lastnameErr = "Only letters are allowed";
return $lastnameErr;
} else {
global $lastname;
$lastname = $lname;
return '';
}
}
function validateUserName($uname) {
if(empty($uname)) {
global $usernameErr;
$usernameErr = "Username is required";
return $usernameErr;
} else if (!preg_match("/^[a-zA-Z0-9 ]*$/", $uname)){ // checks if username contains only letters and digits
global $usernameErr;
$usernameErr = "Only letters and digits are allowed";
return $usernameErr;
} else {
global $username;
$username = $uname;
return '';
}
}
function validatePassword($pword){
if(empty($pword)) {
global $passwordErr;
$passwordErr = "Password is required";
return $passwordErr;
} else if (preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $pword) === 0) {
global $passwordErr;
$passwordErr = "Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit";
return $passwordErr;
} else {
global $password;
$password = $pword;
return '';
}
}
function validateGender($gen){
if(empty($gen)) {
global $genderErr;
$genderErr = "Gender is required";
return $genderErr;
} else {
global $gender;
$gender = $gen;
return '';
}
}
function validateCourse($cour){
if(empty($cour)) {
global $courseErr;
$courseErr = "Select atleast one";
return $courseErr;
} else {
global $course;
$course = $cour;
return '';
}
}
function validateComments($comm){
if(empty($comm)) {
return '';
} else {
global $comments;
$comments = $comm;
return '';
}
}
//renderform();
?>
<html>
<head>
<title>Sample Form</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" id="firstname" value="<?php echo $firstname; ?>" /><span class="error">* <?php echo $firstnameErr; ?></span><br/><br/>
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" id="lastname" value="<?php echo $lastname; ?>" /><span class="error"> <?php echo $lastnameErr; ?></span><br/><br/>
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="<?php echo $username; ?>" /><span class="error">* <?php echo $usernameErr; ?></span><br/><br/>
<label for="password">Password:</label>
<input type="password" name="password" id="password" /><span class="error">* <?php echo $passwordErr; ?></span><br/><br/>
Gender:
<label for="male">Male</label>
<input type="radio" name="gender" id="male" <?php if (isset($gender) && $gender == "male") echo "checked"; ?> value="male" />
<label for="female">Female</label>
<input type="radio" name="gender" id="female" <?php if (isset($gender) && $gender == "female") echo "checked"; ?> value="female" /><span class="error">* <?php echo $genderErr; ?></span><br/><br/>
<label for="course">Course:</label>
PHP<input type="checkbox" name="course[]" id="course" <?php if((!empty($_POST["course"])&& in_array("PHP",$_POST["course"]))){echo "checked";}?> value="PHP" />
HTML<input type="checkbox" name="course[]" id="course" <?php if((!empty($_POST["course"])&& in_array("HTML",$_POST["course"]))){echo "checked";}?> value="HTML" />
CSS<input type="checkbox" name="course[]" id="course" <?php if((!empty($_POST["course"])&& in_array("CSS",$_POST["course"]))){echo "checked";}?> value="CSS" />
Javascript<input type="checkbox" name="course[]" id="course" <?php if((!empty($_POST["course"])&& in_array("Javascript",$_POST["course"]))){echo "checked";}?> value="Javascript" /><span class="error">* <?php echo $courseErr; ?></span><br/><br/>
<label for="comments">Comments:</label><br/>
<textarea name="comments" rows="4" cols="20" id="comments"/><?php echo $comments; ?></textarea><br/><br/>
<input type = "submit" value="Submit" name="submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo "Firstname:" . $firstname;
echo "<br>";
echo "Lastname:" . $lastname;
echo '<br>';
echo "Username:" . $username;
echo '<br>';
echo "Password:" . $password;
echo '<br>';
echo "Gender:" . $gender;
echo '<br>';
global $string;
$string = implode(",",$course);
echo "Course(/s):" . $string;
echo '<br>';
echo "Comments:" . $comments;
echo '<br>';
?>
</body>
</html>
code of index.php(This file is run first)
<?php
define('PROJECT',$_SERVER['DOCUMENT_ROOT'].'PhpSample');
include (PROJECT.'/utilities.php');
include ('constant.php');
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$errors = validate_errors($variables);
$counter = 0;
foreach ($errors as $value) {
if ($value === '') {
$counter++;
}
}
//if there are no errors
if ($counter == 7) {
//database operation
$con = mysqli_connect($host, $user, $pword);
if (!$con) {
echo 'Error connecting to database. Please try again later';
exit;
}
$val = cleanandinsert($variables,$con,$dbname);
mysqli_close($con);
if(!$val){
echo 'Could not register. Please try again later';
exit;
}
header("Location:http://localhost/PhpSample/target.php?vals=" . urlencode(serialize($variables)));
exit;
}
}
include('myform.phtml');
?>
Code of target.php
<?php
include 'process.php';
$Values= unserialize(urldecode($_GET['vals']));
echo "<h2>Your Input:</h2>";
echo "Firstname:".$Values['firstname'];
echo "<br>";
echo "Lastname:".$Values['lastname'] ;
echo '<br>';
echo "Username:".$Values['username'] ;
echo '<br>';
echo "Password:".$Values['password'] ;
echo '<br>';
echo "Gender:".$Values['gender'] ;
echo '<br>';
if (!empty($Values['course'])) {
$string = implode(',', $Values['course']);
} else {
$string = "";
}
echo "Course(/s):" . $string;
echo '<br>';
echo "Comments:".$Values['comments'] ;
echo '<br>';
?>
Code of constant.php
<?php
// define variables and set to empty values
$firstnameErr = $lastnameErr = $usernameErr = $passwordErr = $genderErr = $courseErr = "";
$firstname = $lastname = $username = $password = $gender = $comments = "";
$course = array();
$variables = initialize();
$host = 'localhost';
$user = 'root';
$pword = '';
$dbname = 'mydb';
$tablename = 'userdata';
?>
Code of myform.phtml
<html>
<head>
<title>Sample Form</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<p><span class="error">* required field.</span></p>
<form method="post" action="./index.php">
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" id="firstname" value="<?php if (isset($variables['firstname']) ? print_r($variables['firstname']) : '') ; ?>" /><span class="error">* <?php if (isset($errors['firstname']) ? print_r($errors['firstname']) : '') ; ?></span><br/><br/>
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" id="lastname" value="<?php if (isset($variables['lastname']) ? print_r($variables['lastname']) : '') ; ?>" /><span class="error"> <?php if (isset($errors['lastname']) ? print_r($errors['lastname']) : '') ; ?></span><br/><br/>
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="<?php if (isset($variables['username']) ? print_r($variables['username']) : '') ; ?>" /><span class="error">* <?php if (isset($errors['username']) ? print_r($errors['username']) : '') ; ?></span><br/><br/>
<label for="password">Password:</label>
<input type="password" name="password" id="password" /><span class="error">* <?php if (isset($errors['password']) ? print_r($errors['password']) : '') ; ?></span><br/><br/>
Gender:
<label for="male">Male</label>
<input type="radio" name="gender" id="male" <?php if (isset($variables['gender']) && ($variables['gender'] == "male")) echo "checked"; ?> value="male" />
<label for="female">Female</label>
<input type="radio" name="gender" id="female" <?php if (isset($variables['gender']) && ($variables['gender'] == "female")) echo "checked"; ?> value="female" /><span class="error">* <?php if (isset($errors['gender']) ? print_r($errors['gender']) : '') ; ?></span><br/><br/>
<label for="course">Course:</label>
PHP<input type="checkbox" name="course[]" id="course" <?php echo getChecked("PHP") ?> value="PHP" />
HTML<input type="checkbox" name="course[]" id="course" <?php echo getChecked("HTML") ?> value="HTML" />
CSS<input type="checkbox" name="course[]" id="course" <?php echo getChecked("CSS") ?> value="CSS" />
Javascript<input type="checkbox" name="course[]" id="course" <?php echo getChecked("Javascript") ?> value="Javascript" /><span class="error">* <?php if (isset($errors['course']) ? print_r($errors['course']) : '') ; ?></span><br/><br/>
<label for="comments">Comments:</label><br/>
<textarea name="comments" rows="4" cols="20" id="comments"/><?php if (isset($variables['comments']) ? print_r($variables['comments']) : '') ; ?></textarea><br/><br/>
<input type = "submit" value="Submit" name="submit">
</form>
Code of utilities.php
<?php
/**
* It cleans the variable and returns variable free from cross site cripting.
* #return variable free from whitespaces,stripped of slashes,tags.
*/
function clean($data, $ishtmltype = FALSE) {
if ($ishtmltype) { //for database operation
$data = htmlspecialchars(stripslashes(trim($data)));
return $data;
}
$data = strip_tags(htmlspecialchars(stripslashes(trim($data))));
return $data;
}
/**
* It returns an array of variables which are cleansed with the help of "clean()"
* #return $var array
*/
function initialize() {
$var = array();
$var['firstname'] = isset($_POST['firstname']) ? clean($_POST['firstname']) : '';
$var['lastname'] = isset($_POST['lastname']) ? clean($_POST['lastname']) : '';
$var['username'] = isset($_POST['username']) ? clean($_POST['username']) : '';
$var['password'] = isset($_POST['password']) ? $_POST['password'] : '';
if (!empty($_POST['gender'])) {
$var['gender'] = $_POST['gender'];
} else {
$var['gender'] = '';
}
//var_dump($_POST[gender]);
if (!empty($_POST['course'])) {
$var['course'] = $_POST['course'];
} else {
$var['course'] = '';
}
$var['comments'] = isset($_POST['comments']) ? clean($_POST['comments']) : '';
return $var;
}
/**
* It returns an array of error variables which have error messages in them
* #param type $var array
* #return $errors array
*/
function validate_errors($var) {
$errors = array();
$errors['firstname'] = validateFirstName($var['firstname']); //should return error string or ''
$errors['lastname'] = validateLastname($var['lastname']);
$errors['username'] = validateUserName($var['username']);
$errors['password'] = validatePassword($var['password']);
$errors['gender'] = validateGender($var['gender']);
$errors['course'] = validateCourse($var['course']);
$errors['comments'] = validateComments($var['comments']);
return $errors;
}
/**
* It returns an error message, if any, in the first name
* #param type $fname
* #return string or null if not found
*/
function validateFirstName($fname) {
if (empty($fname)) {
$firstnameErr = "First name is required";
return $firstnameErr;
} else if (!preg_match("/^[a-zA-Z']*$/", $fname)) { // check if name only contains letters and whitespace.Performs a regular expression match
$firstnameErr = "Only letters are allowed";
return $firstnameErr;
}
else if (strlen($fname) < 3){
$firstnameErr = "Atleast 3 characters";
return $firstnameErr;
}
else if (strlen($fname) > 60){
$firstnameErr = "Not more than 60 characters";
return $firstnameErr;
}
return '';
}
/**
* It returns an error message, if any, in the last name
* #param type $lname
* #return string or null if not found
*/
function validateLastName($lname) {
if (empty($lname)) {
return '';
} else if (!preg_match("/^[a-zA-Z ]*$/", $lname)) { // check if name only contains letters and whitespace,performs a regular expression match
$lastnameErr = "Only letters are allowed";
return $lastnameErr;
}
else if (strlen($lname) > 60){
$firstnameErr = "Not more than 60 characters";
return $firstnameErr;
}
return '';
}
/**
* It returns an error message, if any, in the user name
* #param type $uname
* #return string or null if not found
*/
function validateUserName($uname) {
if (empty($uname)) {
$usernameErr = "Username is required";
return $usernameErr;
} else if (!preg_match("/^[a-zA-Z0-9 ]*$/", $uname)) { // checks if username contains only letters and digits
$usernameErr = "Only letters and digits are allowed";
return $usernameErr;
}
else if (strlen($uname) < 3){
$firstnameErr = "Atleast 3 characters";
return $firstnameErr;
}
else if (strlen($uname) > 60){
$firstnameErr = "Not more than 60 characters";
return $firstnameErr;
}
return '';
}
/**
* It returns an error message, if any, in the password
* #param type $pword
* #return string or null if not found
*/
function validatePassword($pword) {
if (empty($pword)) {
$passwordErr = "Password is required";
return $passwordErr;
} else if (preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $pword) === 0) {
$passwordErr = "Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit";
return $passwordErr;
}
return '';
}
/**
* It returns an error message, if any, in the gender
* #param type $gen
* #return string or null if not found
*/
function validateGender($gen) {
if (empty($gen)) {
$genderErr = "Gender is required";
return $genderErr;
} else if (($gen != "male") && ($gen != "female")) {
$genderErr = "Not a valid selection";
return $genderErr;
}
return '';
}
/**
* It returns an error message, if any, in the course
* #param type $cour
* #return string or null if not found
*/
function validateCourse($cour) {
if (empty($cour)) {
$courseErr = "Select atleast one";
return $courseErr;
} else if (array_values($cour) != ("PHP" && "HTML" && "CSS" && "Javascript")) {
$courseErr = "Not a valid selection";
return $courseErr;
}
return '';
}
/**
* It doesnot return an error message, but accepts any content
* #param type $comm
* #return null
*/
function validateComments($comm) {
if (empty($comm)) {
return '';
}
return '';
}
/**
* It removes any special characters in a string and inserts the validated user data into the database
* #param type $variables array
* #param type $con
* #param type $dbname
* #return boolean
*/
function cleanandinsert($variables, $con, $dbname) {
$firstname = mysqli_real_escape_string($con, $variables['firstname']); //The mysqli_real_escape_string() function escapes special characters in a string for use in an SQL statement.
$lastname = mysqli_real_escape_string($con, $variables['lastname']);
$username = mysqli_real_escape_string($con, $variables['username']);
$password = sha1($variables['password']);
$gender = mysqli_real_escape_string($con, $variables['gender']);
$string = implode(',', ($variables['course']));
$course = mysqli_real_escape_string($con, $string);
$comments = mysqli_real_escape_string($con, $variables['comments']);
$sql = "INSERT INTO $dbname.userdata (firstname,lastname,username,password,gender,course,comments)
VALUES ('$firstname','$lastname','$username','$password','$gender','$course','$comments')";
if (!mysqli_query($con, $sql)) {
return FALSE;
}
return TRUE;
}
/**
* It checks the checked checkboxes on the submission of the wrong data i.e it remembers the checked checkbox.
* #param type $course
* #return checked checkbox or null if a checkbox is not checked
*/
function getChecked($course){
if(!empty($_POST['course']) && in_array($course, $_POST["course"])){
return 'checked';
}
return '';
}
?>
You can use ladder if..else structure for your code
in if() you will put your condition and if the condition is false it will go to the error message and then you can put link of the main form, so that the user can go back...
There are many ways for doing this, but the easy way to do this is "Put your Whole form code in php file and just make one file, i am not sure but it should work, the error will be shown below the form for that first write your form code and after write your php script".:)
Related
how to pass the collected input to another page after self validate in php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<body>
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr =$mobileTelNoErr = $sendMethodErr = "";
$forename = $surname = $email = $postalAddress = $landLineTelNo = $mobileTelNo = $sendMethod = "";
if($_SERVER["REQUEST_METHOD"] =="POST"){
$valid = true;
if(empty($_POST["forename"])){
$forenameErr = "Forename is required";
$valid = false; //false
} else {
$forename = test_input($_POST["forename"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["surname"])){
$surnameErr = "Surname is required";
$valid = false; //false
} else {
$surname = test_input($_POST["surname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["postalAddress"])){
$postalAddressErr =" Please enter postal address";
$valid = false; //false
} else {
$postalAddress = test_input($_POST["postalAddress"]);
}
if(empty($_POST["landLineTelNo"])){
$landLineTelNoErr = "Please enter a telephone number";
$valid = false; //false
} else {
$landLineTelNo = test_input($_POST["landLineTelNo"]);
// check if invalid telephone number added
if (!preg_match("/^[0-9 ]{7,}$/",$landLineTelNo)) {
$landLineTelNoErr = "Invalid telephone number entered";
}
}
if(empty($_POST["mobileTelNo"])){
$mobileTelNoErr = "Please enter a telephone number";
$valid = false; //false
} else {
$mobileTelNo = test_input($_POST["mobileTelNo"]);
// check if invalid telephone number added
if (!preg_match("/^[0-9 ]{7,}$/",$mobileTelNo)) {
$mobileTelNoErr = "Invalid telephone number entered";
}
}
if(empty($_POST["email"])){
$emailErr = "Email is required";
$valid = false; //false
} 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["sendMethod"])){
$sendMethodErr = "Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//if valid then redirect
if($valid){
header('Location: userdetail.php');
exit();
}
}
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<nav>
<ul>
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>WireFrame</li>
</ul>
</nav>
<form id = "userdetail" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="forename">Forename: </label>
<input type="text" name="forename" id="forename" value="<?php echo $forename;?>">
<span class="error">* <?php echo $forenameErr;?></span>
</p>
<p>
<label for="surname">Surname:</label>
<input type="text" name="surname" id="surname" value="<?php echo $surname;?>">
<span class="error">* <?php echo $surnameErr;?></span>
</p>
<p>
<label for="postalAddress">Postal Address:</label>
<input type="text" name="postalAddress" id="postalAddress" value="<?php echo $postalAddress;?>">
<span class="error"> </span>
</p>
<p>
<label for="landLineTelNo">Landline Telephone Number:</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" value="<?php echo $landLineTelNo;?>" >
<span class="error"> * <?php echo $landLineTelNoErr;?></span>
</p>
<p>
<label for="mobileTelNo">Moblie:</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" placeholder="example:012-3456789" value="<?php echo $mobileTelNo;?>" />
<span class="error"><?php echo $mobileTelNoErr;?></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" value="<?php echo $email;?>" placeholder="example:123#hotmail.com"/>
<span class="error"> </span>
</p>
<fieldset id="future">
<legend>Lastest news</legend>
<p>
Choose the method you recommanded to recevive the lastest information
</p>
<br>
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="SMS") echo "checked";?> value="SMS">
SMS
<span class="error">* <?php echo $sendMethodErr;?></span>
</fieldset>
<p><span class="error">* required field.</span></p>
<input type="checkbox" name="checkbox" value="check" id="agree" />
I have read and agree to the Terms and Conditions and Privacy Policy
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
</fieldset>
</form>
</div>
</body>
</html>
here is my php form...
it can validate itself in the same page but couldn't pass the data to another php page....
here is my another php code...
<?php
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr =$mobileTelNoErr = $sendMethodErr = "";
$forename = $surname = $email = $postalAddress = $landLineTelNo = $mobileTelNo = $sendMethod = "";
echo "<h1>Successfull submission :</h1>";
echo "<p>Forename : $forename <p/>";
echo "<p>Surname : $surname <p/>";
echo "<p>Email: $email</p>";
echo "<p>Post Address: $postalAddress</p>";
echo "<p>Landline: $landLineTelNo</p>";
echo "<p>Mobile : $mobileTelNo</p>";
echo "<p>Contact method: $sendMethod";
?>
You can use $_SESSION variables.
PHP $_SESSIONS
PHP Sessions and Cookies
So after the users has been validated set $_SESSION['surname'] = $surname;
Then on the top of each page add session_start(); to the top.
Then Under that add
if (isset($_SESSION['surname'])) {
$surname = $_SESSION['surname'];
} else {
die();
}
View the PHP docs for a more thorough understanding.
You may also want to look into setting up a MYSQL database if you want users to be able to create accounts.
Edit: form page
if($valid){
$_SESSION['surname'] = $surname;
$_SESSION['postalAddress'] = $postalAddress;
header('Location: userdetail.php');
exit();
}
my form action is php_self so that it can validate the form...
what i want to do is after the form is submited, then the data is connect and send to sql....
i already import my sql table and it have a few data recorded inside the table....
so how can i connect to the sql??
and also where i should write my connect sql code in???
here is my php form code....
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function disableSubmit() {
document.getElementById("submit").disabled = true;
}
function activateButton(element) {
if(element.checked) {
document.getElementById("submit").disabled = false;
}
else {
document.getElementById("submit").disabled = true;
}
}
</script>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
<body onload="disableSubmit()">
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr = $mobileTelNoErr = $sendMethodErr = $checkErr ="";
$valid = true;
// if forename is null , make it null , else test_input()
$forename = empty($_POST["forename"]) ? NULL : test_input($_POST["forename"]);
// if surname is null , make it null , else test_input()
$surname = empty($_POST["surname"]) ? NULL : test_input($_POST["surname"]);
// if postalAddress is null , make it null , else test_input()
$postalAddress = empty($_POST["postalAddress"]) ? NULL : test_input($_POST["postalAddress"]);
// if landLineTelNo is null , make it null , else test_input()
$landLineTelNo = empty($_POST["landLineTelNo"]) ? NULL : test_input($_POST["landLineTelNo"]);
// if mobileTelNo is null , make it null , else test_input()
$mobileTelNo = empty($_POST["mobileTelNo"]) ? NULL : test_input($_POST["mobileTelNo"]);
//email
$email = empty($_POST["email"]) ? NULL : test_input($_POST["email"]);
// if sendMethod is null , make it null , else test_input()
$sendMethod = empty($_POST["sendMethod"]) ? NULL : test_input($_POST["sendMethod"]);
if (isset($_POST["submit"])){
//check forename
if($forename === NULL) {
//forename is empty
$forenameErr = "*Forename is required";
$valid = false;
} else {
//check characters
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
$valid = false;
}
}
//check surname
if($surname === NULL){
//surname is empty
$surnameErr = "*Surname is required";
$valid = false; //false
} else {
//check charaters
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "*Only letters and white space allowed";
$valid = false;
}
}
//check address
if (!preg_match("/^[a-zA-Z0-9\-\\,. ]*$/", $postalAddress)) {
// check characters
$postalAddressErr = "*Invalid Postal Address";
$valid = false;//false
}
// check if invalid telephone number added
if (!preg_match("/^$|^[0-9]{12}$/",$landLineTelNo)) {
//check number
$landLineTelNoErr = "*Only 12 digit number can be entered";
$valid = false;//false
}
//check valid mobiel tel no
if (!preg_match("/^$|^[0-9]{11}$/",$mobileTelNo)) {
//check number
$mobileTelNoErr = "*Only 11 digit number can be entered";
$valid = false;//false
}
//check valid email
if (isset($email) && !filter_var($email, FILTER_VALIDATE_EMAIL))
{ $emailErr = "*Invalid email format";
$valid = false;//false
}
//check sendMethod
if($sendMethod === NULL){
//send method is empty
$sendMethodErr = "*Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//sendmethod link to information filled
if (isset($sendMethod) && $sendMethod=="email" && $email ==NULL){
$emailErr ="*Email is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="post" && $postalAddress ==NULL){
$postalAddressErr ="*Postal Address is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="SMS" && $mobileTelNo ==NULL){
$mobileTelNoErr ="*Mobile number is required ";
$valid = false;
}
if(empty($_POST['agree']) || $_POST['agree'] != 'agree') {
$checkErr ="Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy";
}
//if valid then redirect
if($valid){
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
$_SESSION['email'] = $email;
$_SESSION['postalAddress'] = $postalAddress;
$_SESSION['landLineTelNo'] = $landLineTelNo;
$_SESSION['mobileTelNo'] = $mobileTelNo;
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
}
} else{
//user did not submit form!
}
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<nav>
<ul>
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>WireFrame</li>
</ul>
</nav>
<form id = "userdetail" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="forename">Forename: </label>
<input type="text" name="forename" id="forename" value="<?php echo $forename;?>">
<span class="error"> <?php echo $forenameErr;?></span>
</p>
<p>
<label for="surname">Surname:</label>
<input type="text" name="surname" id="surname" value="<?php echo $surname;?>">
<span class="error"> <?php echo $surnameErr;?></span>
</p>
<p>
<label for="postalAddress">Postal Address:</label>
<input type="text" name="postalAddress" id="postalAddress" value="<?php echo $postalAddress;?>">
<span class="error"> <?php echo $postalAddressErr;?></span>
</p>
<p>
<label for="landLineTelNo">Landline Telephone Number:</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" value="<?php echo $landLineTelNo;?>" >
<span class="error"> <?php echo $landLineTelNoErr;?></span>
</p>
<p>
<label for="mobileTelNo">Moblie:</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" value="<?php echo $mobileTelNo;?>" >
<span class="error"> <?php echo $mobileTelNoErr;?></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" value="<?php echo $email;?>">
<span class="error"> </span> <?php echo $emailErr;?> </span>
</p>
<fieldset id="future">
<legend>Lastest news</legend>
<p>
Choose the method you recommanded to recevive the lastest information
</p>
<br>
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="SMS") echo "checked";?> value="SMS">
SMS
<span class="error"> <?php echo $sendMethodErr;?></span>
</fieldset>
<p><span class="error">* required field.</span></p>
<input type="checkbox" name="terms" id="terms" onchange="activateButton(this)">
I Agree Terms & Coditions
<br><br>
<input type="submit" name="submit" id="submit">
</fieldset>
</form>
</div>
</body>
</html>
the userdetail.php is the page that shows the information that user submit...
so where and how i can insert the data in to sql....
You should write your SQL code within $valid.
Let me illustrate below:
Note: I've used default credentials: Hostname = localhost, username = root, password = '', database name = my_database.
You may refer to this: mysqli_connect()
if($valid){
echo "Valid data<br/>"; // Debugging code
echo '</pre>';
print_r($_POST);
exit;
/* SQL code starts */
$con = mysqli_connect("localhost", "root", "", "my_database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO...."; // Your insert query
$query = mysqli_query($con,$sql) or die(mysqli_error($con));
/* SQL code ends */
if ($query) { // Add this condition. Session should be written only when SQL query is successful
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
..........
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
} else {
echo "Unable to insert";
}
} else{
echo "Invalid data<br/>"; // Debugging code
echo '</pre>';
print_r($_POST);
exit;
}
Hope this helps.
I am having a very weird problem here, my if else statements just get ignored after I submit the form and all values entered or not entered goes through to the database.
Firstly, I pre populate all fields with info submitted during registration then users can edit and change their info - this works fine but I decided to add it as I don't know whether it might have a hand in this mystery error.
Here's my code to retrieve details, the variables holding retrieved values are echoed in their respective fields in the form.
<?php
include("connect.php");
$results = $conn->query("SELECT username, first_name,last_name, email,phone,address FROM users WHERE email='$user_logged'");
while ($row = $results->fetch_assoc()) {
$u_name = $row['username'];
$f_name = $row['first_name'];
$l_name = $row['last_name'];
$email = $row['email'];
$phone = $row['phone'];
$address = $row['address'];
}
$results->free();
$conn->close();
?>
It's not checking for empty fields. Functions test_input and preg_match do not work alsko. The form just submits and database gets updated.
I have spent 2 days going through to look for where the error might be but I can't detect it.
<?php
$user_logged = $_SESSION['logged_in'];
if (isset($_POST['btnUpdate'])) {
include("connect.php");
$phoneErr = $f_nameErr = $l_nameErr = "";
$user_email = $first_name = $last_name = $phone_upadate = $address_updated = "";
if (empty($_POST["fname"])) {
$f_nameErr = "First Name is required";
} else {
$first_name = test_input($_POST["fname"]);
if (!preg_match("/^[a-zA-Z ]*$/", $first_name)) {
$f_nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["lname"])) {
$l_nameErr = "Last Name is required";
} else {
$last_name = test_input($_POST["lname"]);
if (!preg_match("/^[a-zA-Z ]*$/", $last_name)) {
$l_nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone No is required";
} else {
$phone_upadate = test_input($_POST['phone']);
if (!preg_match("/^[0-9]{0,18}$/", $phone_upadate)) {
$phoneErr = "Only numbers and white space allowed";
}
}
$user_email = $_POST['email'];
$address_updated = $_POST['txtaddress'];
$results = $conn->query("UPDATE users SET
first_name='$first_name',last_name='$last_name',
email='$user_email',phone='$phone_upadate',
address='$address_updated'
WHERE email='$user_logged'");
if ($results) {
header("Location: edit-info.php");
} else {
print 'Error : (' . $conn->errno . ') ' . $conn->error;
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Here is my html code
<form action="edit-info.php" method="POST">
<?php $username_error="can't be changed"; ?>
<p>Username</p>
<p><input type="text" name="username" id="txtuser" value="<?php echo $u_name; ?>" readonly></input><span id="error"><?php echo $username_error?></span></p>
<p>First Name</p>
<p><input type="text" name="fname" id="txtuser" value="<?php echo $f_name; ?>"></input><span id="error"><?php echo $f_nameErr;?></span></p>
<p>Last Name</p>
<p><input type="text" name="lname" id="txtuser" value="<?php echo $l_name; ?>" ></input><span id="error"><?php echo $l_nameErr;?></span></p>
<p>Email</p>
<p> <input type="text" name="email" id="txtuser" value="<?php echo $email; ?>" readonly></input><span id="error"><?php echo $f_nameErr;?></span></p>
<p>Phone</p>
<p><input type="text" name="phone" id="txtuser" value="<?php echo $phone; ?> " ></input></p>
<span id="error"><?php echo $phoneErr;?></span>
<p>Address</p>
<p><textarea id="txtaddress" name="txtaddress" cols="40" rows="10" ><?php echo $address; ?></textarea></p>
<p><input type="submit" name="btnUpdate" value="UPDATE" /></p>
</form>
You need to check the values of $phoneErr, $f_nameErr, $l_nameErr before you proceed UPDATE like this
if(empty($phoneErr) && empty($f_nameErr) && empty($l_nameErr)){
$results = $conn->query("UPDATE users SET first_name='$first_name',last_name='$last_name', email='$user_email',phone='$phone_upadate',address='$address_updated' WHERE email='$user_logged'");
}
Because when you have any validation error in empty or preg_match you are updating these values. And without checking these $phoneErr, $f_nameErr, $l_nameErr variables you are proceeding to UPDATE
You could try replacing
"/^[a-zA-Z ]*$/"
with
"/^[a-zA-Z ]+$/"
Notice we are replacing the multiplication sign with a summation sign.
My php self-validating form is submitting to sql database whether the characters entered into form fields are appropriate or not...How do stop it from submitting until the conditions for each form field are met?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>RSG Contact Us</title>
<script>
// $(function () {
// $('form').on('submit', function (e) {
// $.ajax({
// type: 'post',
// url: 'contact.php',
// data: $('form').serialize(),
// success: function () {
// alert('Thank you! your form has been submitted');
// }
// });
// e.preventDefault();
// });
// });
</script>
</head>
<body>
<div id="contactuscall">
<?php
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$firstnameErr = $lastnameErr = $emailErr = $cellphoneErr = $genDerErr = $dognameErr = $BreedErr = $reasonErr = "";
$firstname = $lastname = $email = $cellphone = $genDer = $dogname = $Breed = $reasoN= $freecomments = "";
//if conditional statement stops PHP from looking for variable values until the submit button is hit
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// check if a first name was provided
if (empty($_POST["firstname"]))
{$firstnameErr = "A first name is required";}
else
{
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
{$firstnameErr = "Only letters and white space allowed";}
}
//check if a last name was provided
if (empty($_POST["lastname"]))
{$lastnameErr = "A last name is required";}
else
{
$lastname = test_input($_POST["lastname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname))
{
$lastnameErr = "Only letters and white space allowed";
}
}
// check if an email was provided
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["cellphone"]))
{$cellphoneErr = "Please provide a phone number";}
else {
$cellphone = test_input($_POST["cellphone"]);
// Regular Expression to allow only valid phone number formats, including numbers, spaces, dashes, extensions
if (!preg_match("/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/",$cellphone))
{$cellphoneErr = "Invalid format";}
}
if (empty($_POST["dogname"]))
{$dognameErr = "A doggy name is required";}
else {
$dogname = test_input($_POST["dogname"]);
// check if dogname only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$dogname))
{$dognameErr = "Only letters and white space allowed";}
}
if (empty($_POST["Breed"]))
{$BreedErr = "A breed name is required";}
else {
$Breed = test_input($_POST["Breed"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Breed))
{$BreedErr = "Only letters and white space allowed";}
}
if(empty($_POST['genDer']))
{$genDerErr= "You forgot to select a Gender!";}
else {
$genDer=($_POST['genDer']);
}
//make sure one of the services requested checkboxes are checked
$reasoN = $_POST['reasoN'];
if(empty($reasoN))
{
$reasonErr="You didn't select any services.";
}
else
{
$N = count($reasoN);
$reasonErr="You selected $N services(s): ";
}
// if comment section is not empty then run test_input function to purge possible malicious code
if (empty($_POST["freecomments"]))
{$freecomments = "";}
else
{$freecomments = test_input($_POST["freecomments"]);}
}
$host="fdb3.biz.nf"; //localhost
$dbuser="1546259_rsginfo"; //user
$dbpass="RSGnow12"; //pass
$dbname="1546259_rsginfo"; //db name
// Create connection
$conn=mysqli_connect($host,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//create query
$sql= "INSERT INTO customer (fname, lname, email, phone, comments)VALUES ('$firstname', '$lastname', '$email', '$cellphone', '$freecomments')";
$sql2= "INSERT INTO DogInfo (DogName, Breed, Lookingfor)VALUES ('$dogname', '$Breed', '$reasoN')";
// execute query
mysqli_query($conn,$sql);
mysqli_query($conn, $sql2);
// close connection
mysqli_close($conn)
?>
<form id="form1" name="form1" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
<fieldset id="field1">
<legend id="legend1">Contact info:</legend>
<hr />
First name: <input type="text" id="firstname" name="firstname" size="30" class="textfield" value="<?php echo $firstname;?>">
<span class="error">* <?php echo $firstnameErr;?></span>
E-mail: <input type="text" size="30" name="email" class="textfield" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span><br />
Last name: <input type="text" id="lastname" name="lastname" size="30" class="textfield" value="<?php echo $lastname;?>">
<span class="error">* <?php echo $lastnameErr;?></span>
Cell: <input type="text" id="cellphone" name="cellphone" size="30" class="textfield" value="<?php echo $cellphone;?>">
<span class="error">* <?php echo $cellphoneErr;?></span><br />
</fieldset>
<fieldset id="field2">
<legend id="legend2">Doggie info:</legend>
<hr />
Name: <input type="text" id="dogname" name="dogname" size="20" class="textfield" value="<?php echo $dogname;?>"><span class="error">* <?php echo $dognameErr;?></span>
Breed: <input type="text" id="Breed" name="Breed" size="20" class="textfield" value="<?php echo $Breed;?>"><span class="error">* <?php echo $BreedErr;?></span>
<p>
Gender:<select name="genDer" class="textfield">
<option value="">--</option>
<option value="Intact Male" <?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Intact Male" ? "selected" : "" ?>>Intact Male</option>
<option value="Neutered Male"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Neutered Male" ? "selected" : "" ?>>Neutered Male</option>
<option value="Intact Female"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Intact Female" ? "selected" : "" ?>>Intact Female</option>
<option value="Neutered Female"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Neutered Female" ? "selected" : "" ?>>Neutered Female</option>
</select><span class="error">* <?php echo $genDerErr;?></span>
</p>
</fieldset>
<fieldset id="field3">
<legend id="legend3">Services Required:</legend>
<hr />
<input type="checkbox" name="reasoN[]" value="walkSale"
<?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking for a Dog Walker!
<input type="checkbox" name="reasoN[]" value="RawSale"
<?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking to purchase Raw Food!
<input type="checkbox" name="reasoN[]" value="groomSale"
<?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking for a Dog Groomer!
<span class="error">* <?php echo $reasonErr;?></span>
<?php echo $reasonConfirm;?>
</fieldset>
<fieldset id="field4">
<legend id="legend4">Comments & Questions</legend>
<hr />
<textarea rows="7" cols="90" id="freecomments" name="freecomments"><?php echo $freecomments;?></textarea>
</fieldset>
<input id="submit" type="submit" name="submit" value="submit">
</form>
</div>
<?php
echo "<h2>Your Input:</h2>";
echo $firstname;
echo "<br>";
echo $lastname;
echo "<br>";
echo $email;
echo "<br>";
echo $cellphone;
echo "<br>";
echo $dogname;
echo "<br>";
echo $Breed;
echo "<br>";
echo $genDer;
echo "<br>";
echo $reasoN;
echo "<br>";
echo $freecomments;
?>
</body>
</html>
Your code actually tries to insert values in to the table whether or not the validation is successful. The easiest and the quickest solution for this is to use a boolean flag.
eg:
// ...
$formValid = true; // Define a boolean and set to true before validating
//if conditional statement stops PHP from looking for variable values until the submit button is hit
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// check if a first name was provided
if (empty($_POST["firstname"]))
{
$firstnameErr = "A first name is required";
} else {
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
{
$firstnameErr = "Only letters and white space allowed";
$formValid = false; // Invalid input - set the flag to false
}
}
}
// ....
// Eventually wrap the mysql logic inside a condition
if ($formValid)
{
// Create connection
$conn=mysqli_connect($host,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//create query
$sql= "INSERT INTO customer (fname, lname, email, phone, comments)VALUES ('$firstname', '$lastname', '$email', '$cellphone', '$freecomments')";
$sql2= "INSERT INTO DogInfo (DogName, Breed, Lookingfor)VALUES ('$dogname', '$Breed', '$reasoN')";
// execute query
mysqli_query($conn,$sql);
mysqli_query($conn, $sql2);
// close connection
mysqli_close($conn);
}
// ... rest of your code
after i submit the form, the data in the form is sent to sql...
the unfill text field sending nothing to the table....
how to auto assign the word "NULL" in sql if the user do not fill in anyhting in the form....
here is my php form code
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function disableSubmit() {
document.getElementById("submit").disabled = true;
}
function activateButton(element) {
if(element.checked) {
document.getElementById("submit").disabled = false;
}
else {
document.getElementById("submit").disabled = true;
}
}
</script>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
<body onload="disableSubmit()">
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr = $mobileTelNoErr = $sendMethodErr = $checkErr ="";
$valid = true;
// if forename is null , make it null , else test_input()
$forename = empty($_POST["forename"]) ? NULL : test_input($_POST["forename"]);
// if surname is null , make it null , else test_input()
$surname = empty($_POST["surname"]) ? NULL : test_input($_POST["surname"]);
// if postalAddress is null , make it null , else test_input()
$postalAddress = empty($_POST["postalAddress"]) ? NULL : test_input($_POST["postalAddress"]);
// if landLineTelNo is null , make it null , else test_input()
$landLineTelNo = empty($_POST["landLineTelNo"]) ? NULL : test_input($_POST["landLineTelNo"]);
// if mobileTelNo is null , make it null , else test_input()
$mobileTelNo = empty($_POST["mobileTelNo"]) ? NULL : test_input($_POST["mobileTelNo"]);
//email
$email = empty($_POST["email"]) ? NULL : test_input($_POST["email"]);
// if sendMethod is null , make it null , else test_input()
$sendMethod = empty($_POST["sendMethod"]) ? NULL : test_input($_POST["sendMethod"]);
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST["submit"])){
//check forename
if($forename === NULL) {
//forename is empty
$forenameErr = "*Forename is required";
$valid = false;
} else {
//check characters
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
$valid = false;
}
}
//check surname
if($surname === NULL){
//surname is empty
$surnameErr = "*Surname is required";
$valid = false; //false
} else {
//check charaters
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "*Only letters and white space allowed";
$valid = false;
}
}
//check address
if (!preg_match("/^[a-zA-Z0-9\-\\,. ]*$/", $postalAddress)) {
// check characters
$postalAddressErr = "*Invalid Postal Address";
$valid = false;//false
}
// check if invalid telephone number added
if (!preg_match("/^$|^[0-9]{12}$/",$landLineTelNo)) {
//check number
$landLineTelNoErr = "*Only 12 digit number can be entered";
$valid = false;//false
}
//check valid mobiel tel no
if (!preg_match("/^$|^[0-9]{11}$/",$mobileTelNo)) {
//check number
$mobileTelNoErr = "*Only 11 digit number can be entered";
$valid = false;//false
}
//check valid email
if (isset($email) && !filter_var($email, FILTER_VALIDATE_EMAIL))
{ $emailErr = "*Invalid email format";
$valid = false;//false
}
//check sendMethod
if($sendMethod === NULL){
//send method is empty
$sendMethodErr = "*Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//sendmethod link to information filled
if (isset($sendMethod) && $sendMethod=="email" && $email ==NULL){
$emailErr ="*Email is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="post" && $postalAddress ==NULL){
$postalAddressErr ="*Postal Address is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="SMS" && $mobileTelNo ==NULL){
$mobileTelNoErr ="*Mobile number is required ";
$valid = false;
}
if(empty($_POST['agree']) || $_POST['agree'] != 'agree') {
$checkErr ="Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy";
}
//connect to sql
if($valid){
/* SQL code starts */
$con = mysqli_connect("localhost", "root", "", "chollerton");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = $sql = "INSERT INTO ct_expressedinterest (forename, surname, email, postalAddress, landLineTelNo, mobileTelNo ,sendMethod) VALUES ('$forename', '$surname', '$email', '$postalAddress', '$landLineTelNo', '$mobileTelNo' ,'$sendMethod')";
$query = mysqli_query($con,$sql) or die(mysqli_error($con));
//if valid then redirect
if($valid){
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
$_SESSION['email'] = $email;
$_SESSION['postalAddress'] = $postalAddress;
$_SESSION['landLineTelNo'] = $landLineTelNo;
$_SESSION['mobileTelNo'] = $mobileTelNo;
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
}else {echo "Unable to insert";
}
} else{
//user did not submit form!
}
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<nav>
<ul>
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>WireFrame</li>
</ul>
</nav>
<form id = "userdetail" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="forename">Forename: </label>
<input type="text" name="forename" id="forename" value="<?php echo $forename;?>">
<span class="error"> <?php echo $forenameErr;?></span>
</p>
<p>
<label for="surname">Surname:</label>
<input type="text" name="surname" id="surname" value="<?php echo $surname;?>">
<span class="error"> <?php echo $surnameErr;?></span>
</p>
<p>
<label for="postalAddress">Postal Address:</label>
<input type="text" name="postalAddress" id="postalAddress" value="<?php echo $postalAddress;?>">
<span class="error"> <?php echo $postalAddressErr;?></span>
</p>
<p>
<label for="landLineTelNo">Landline Telephone Number:</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" value="<?php echo $landLineTelNo;?>" >
<span class="error"> <?php echo $landLineTelNoErr;?></span>
</p>
<p>
<label for="mobileTelNo">Moblie:</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" value="<?php echo $mobileTelNo;?>" >
<span class="error"> <?php echo $mobileTelNoErr;?></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" value="<?php echo $email;?>">
<span class="error"> </span> <?php echo $emailErr;?> </span>
</p>
<fieldset id="future">
<legend>Lastest news</legend>
<p>
Choose the method you recommanded to recevive the lastest information
</p>
<br>
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="SMS") echo "checked";?> value="SMS">
SMS
<span class="error"> <?php echo $sendMethodErr;?></span>
</fieldset>
<p><span class="error">* required field.</span></p>
<input type="checkbox" name="terms" id="terms" onchange="activateButton(this)">
I Agree Terms & Coditions
<br><br>
<input type="submit" name="submit" id="submit">
</fieldset>
</form>
</div>
</body>
</html>
In your database, what's the default value of the particular field?
It should be set to NULL as default. In that case, if you're not inserting any data for that particular field, it will insert NULL.