How to validate forms when everytime action is on same page - php

I am trying to insert form field values after validating the form.
I develope a seperate php file validate1.php to insert the form field values in database and another file describing form and its validation is in connection.php
When I run connection.php, form fields are getting validated only once,and after form is submitted after that i enter anything.Which should not be happened.
My connection.php is
<html>
<head>
<title></title>
<style> .error {color:#ff0000;} </style>
</head>
<body>
<?php
$companyNameErr = $addressErr = $emailErr = $contactErr = "";
$companyName = $address = $email = $contact = $description = "";
function test_data($data)
{
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
$errors = array();
if ( $_SERVER["REQUEST_METHOD"] =="POST" )
{
$companyName=$_POST["companyName"];
if( empty($companyName) )
{
$companyNameErr = "Please Enter Company Name";
$errors[]= $companyNameErr ;
}
else
{
if( !preg_match("/^[a-zA-Z ]*$/",$companyName) )
{
$companyNameErr = "Invalid Company Name";
$errors[]= $companyNameErr ;
}
else
{
$companyName=test_data($companyName);
}
}
$address=$_POST["address"];
if( empty($address) )
{
$addressErr = "Please Enter Address";
$errors[]= $addressErr ;
}
else
{
$address=test_data($address);
}
$email=$_POST["email"];
if( empty($email) )
{
$emailErr = "Please Enter Email";
$errors[]= $emailErr ;
}
else
{
if( !filter_var($email, FILTER_VALIDATE_EMAIL) )
{
$emailErr = "Invalid Email";
$errors[]= $emailErr ;
}
else
{
$email=test_data($email);
}
}
$contact=$_POST["contact"];
if( empty($contact) )
{
$contactErr = "Please Enter Contact Number";
$errors[]= $contactErr ;
}
else
{
if( !preg_match("/^[0-9]*$/",$contact ) )
{
$contactErr = "Invalid Contact";
$errors[]= $contactErr ;
}
else
{
$contact=test_data($contact);
}
}
}
?>
<form name="myform" method="post" action="<?php if(empty($errors)){ echo $_SERVER["PHP_SELF"]; }else{ echo "validate1.php"; }?>" >
<table>
<tr>
<td>Company Name</td>
<td><input type="text" name="companyName" value ="<?php if(isset($_POST['companyName']) && empty($companyNameErr)){ echo $_POST['companyName'];} else {echo '';}?>" required ><span class="error"><sup>*</sup><?php echo $companyNameErr; ?></span></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" value ="<?php if(isset($_POST['address']) && empty($addressErr)){ echo $_POST['address'];} else {echo '';}?>" required><span class="error"><sup>*</sup><?php echo $addressErr; ?></span></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value ="<?php if(isset($_POST['email']) && empty($emailErr)){ echo $_POST['email'];} else {echo '';}?>" required><span class="error"><sup>*</sup><?php echo $emailErr; ?></span></td>
</tr>
<tr>
<td>Contact</td>
<td>+91-<input type="text" name="contact" value ="<?php if(isset($_POST['contact']) && empty($contactErr)){ echo $_POST['contact'];} else {echo '';}?>" required maxlength="10" minlength="10"><span class="error"><sup>*</sup><?php echo $contactErr; ?></span></td>
</tr>
<tr>
<td>Description</td>
<td><textarea name="description" cols="60" rows="3"></textarea></td>
</tr>
</table>
<input type="submit" name="submit" value="submit">
</form>
</body>
and Validate1.php is
<html>
<head>
<title></title>
</head>
<body>
<?php
$servername="localhost";
$username="root";
$password="";
$conn = new mysqli($servername, $username, $password, 'mydatabase');
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$conn->query("CREATE DATABASE IF NOT EXISTS `MyDataBase`");
$conn->query("CREATE TABLE IF NOT EXISTS MyDataBase.company_details( `comp_id` INT AUTO_INCREMENT PRIMARY KEY,`company_name` VARCHAR(50) NOT NULL,`address` VARCHAR(70) NOT NULL,`email` VARCHAR(30) NOT NULL,`contact` INT(13) NOT NULL,`description` VARCHAR(150))");
$conn->query("INSERT INTO company_details (company_name, address, email, contact, description ) VALUES ( '".$_POST['companyName']."', '".$_POST['address']."', '".$_POST['email']."', '".$_POST['contact']."', '".$_POST['description']."')");
$conn->close();
?>
</body>

Try the following code
N:B : Make sure you have used sql injection prevention techniques when posting form data.
connection.php
<?php
session_start();
$companyName = $address = $email = $contact = $description = "";
function test_data($data)
{
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
$_SESSION['error'] = array();
$_SESSION['resend'] = array();
if ( $_SERVER["REQUEST_METHOD"] =="POST")
{
$companyName=$_POST["companyName"];
if(empty($companyName) )
$_SESSION['error']['companyNameErr'] = "Please Enter Company Name";
else
{
if( !preg_match("/^[a-zA-Z ]*$/",$companyName) )
$_SESSION['error']['companyNameErr'] = "Invalid Company Name";
else
$_SESSION['resend']['companyName'] = test_data($companyName);
}
$address=$_POST["address"];
if(empty($address) )
$_SESSION['error']['addressErr'] = "Please Enter Address";
else
$_SESSION['resend']['address'] = test_data($address);
$email=$_POST["email"];
if(empty($email))
$_SESSION['error']['emailErr'] = "Please Enter Email";
else
{
if( !filter_var($email, FILTER_VALIDATE_EMAIL) )
$_SESSION['error']['emailErr'] = "Invalid Email";
else
$_SESSION['resend']['email'] = test_data($email);
}
$contact=$_POST["contact"];
if(empty($contact))
$_SESSION['error']['contactErr'] = "Please Enter Contact Number";
else
{
if( !preg_match("/^[0-9]*$/",$contact ) )
$_SESSION['error']['contactErr'] = "Invalid Contact";
else
$_SESSION['resend']['contact'] = test_data($contact);
}
$description=$_POST["description"];
$_SESSION['resend']['description'] = test_data($description);
if(empty($_SESSION['error'])){
header('location:validate1.php');
exit;
}
}
?>
<html>
<head>
<title></title>
<style> .error {color:#ff0000;} </style>
</head>
<body>
<form name="myform" method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" >
<table>
<tr>
<td>Company Name</td>
<td><input type="text" name="companyName" value ="<?php if(isset($_SESSION['resend']['companyName']) && empty($_SESSION['error']['companyNameErr'])){ echo $_SESSION['resend']['companyName'];} else {echo '';}?>" required ><span class="error"><sup>*</sup><?php if(isset($_SESSION['error']['companyNameErr'])) echo $_SESSION['error']['companyNameErr']; ?></span></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" value ="<?php if(isset($_SESSION['resend']['address']) && empty($_SESSION['error']['addressErr'])){ echo $_SESSION['resend']['address'];} else {echo '';}?>" required><span class="error"><sup>*</sup><?php if(isset($_SESSION['error']['addressErr'])) echo $_SESSION['error']['addressErr']; ?></span></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value ="<?php if(isset($_SESSION['resend']['email']) && empty($_SESSION['error']['emailErr'])){ echo $_SESSION['resend']['email'];} else {echo '';}?>" required><span class="error"><sup>*</sup><?php if(isset($_SESSION['error']['emailErr'])) echo $_SESSION['error']['emailErr']; ?></span></td>
</tr>
<tr>
<td>Contact</td>
<td>+91-<input type="text" name="contact" value ="<?php if(isset($_SESSION['resend']['contact']) && empty($_SESSION['error']['contactErr'])){ echo $_SESSION['resend']['contact'];} else {echo '';}?>" required maxlength="10" minlength="10"><span class="error"><sup>*</sup><?php if(isset($_SESSION['error']['contactErr'])) echo $_SESSION['error']['contactErr']; ?></span></td>
</tr>
<tr>
<td>Description</td>
<td><textarea name="description" cols="60" rows="3"><?php if(isset($_SESSION['resend']['description'])) echo $_SESSION['resend']['description'];?></textarea></td>
</tr>
</table>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
Validate1.php
<?php
session_start();
if(isset($_SESSION['resend'])){
$servername="localhost";
$username="root";
$password="";
$conn = new mysqli($servername, $username, $password, 'test');
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
//$conn->query("CREATE DATABASE IF NOT EXISTS `MyDataBase`");
$conn->query("CREATE TABLE IF NOT EXISTS test.company_details( `comp_id` INT AUTO_INCREMENT PRIMARY KEY,`company_name` VARCHAR(50) NOT NULL,`address` VARCHAR(70) NOT NULL,`email` VARCHAR(30) NOT NULL,`contact` INT(13) NOT NULL,`description` VARCHAR(150))");
$result = $conn->query("INSERT INTO company_details (company_name, address, email, contact, description ) VALUES ( '".$_SESSION['resend']['companyName']."', '".$_SESSION['resend']['address']."', '".$_SESSION['resend']['email']."', '".$_SESSION['resend']['contact']."', '".$_SESSION['resend']['description']."')");
$conn->close();
unset ($_SESSION['resend']);
unset ($_SESSION['error']);
header('location:connection.php');
exit;
}
?>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>

Related

Return the entered data in a form if the error array is empty

i have this code
first file is a form that gets data and perform some basic email validation
second file gets all data and performs php validation and returns error messages that are stored in an array if the user inputs something wrong.
my question is that how can i display the contents of the form if there is no errors and the error array is empty.
<?php
$error = $_GET['message'];
?>
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
function validateEmail()
{
var email = document.getElementById('email').value;
var reEmail = document.getElementById('reEmail').value;
atpos = email.indexOf("#");
dotpos = email.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email")
document.getElementById('email').focus() ;
return false;
}
if (email === reEmail){
return true;
}
alert("emails don't match!");
return false;
}
</script>
</head>
<body>
<div>
<?php
if ($error == ""){
}
else{
foreach ($error as $key => $value) {
echo "<h1>". $value . "</h1>";
}
}
?>
</div>
<form action="registerExec.php" method="post" name="myForm" onsubmit="return(validateEmail());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td align="right">Email</td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td align="right">Retype Email</td>
<td><input type="text" name="reEmail" id="reEmail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
second file:
<?php
$email = $_POST['email'];
$zip = $_POST['zip'];
$name = $_POST['name'];
$message = array(" ");
$goodjob = 'goodjob';
if ($email == "" || $zip == "" || $name ==""){
array_push($message, "Email, Zip, Name should not be empty!");
// chedk if any of these fields is empty
}
if ($name != ""){
if (is_numeric($name)) {
array_push($message, "don't include numberss in name");
}
}
if (is_numeric ($zip) ){
} else {
array_push($message, "zip is not a number!");
}
if (strlen($zip) != 5){
array_push($message, "Wrong Zip!");
}
$finalmessage = http_build_query(array('message' => $message));
header("Location: http://localhost/register/classexercise.php?".$finalmessage);
?>
Here, try this, let me know if you are expecting something else.
<?php
$error = $_GET['message'];
?>
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
function validateEmail(){
var email = document.getElementById('email').value;
var reEmail = document.getElementById('reEmail').value;
atpos = email.indexOf("#");
dotpos = email.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email")
document.getElementById('email').focus() ;
return false;
}
if (email === reEmail){
return true;
}
alert("emails don't match!");
return false;
}
</script>
</head>
<body>
<div>
<?php
if ($error == ""){
}
else{
foreach ($error as $key => $value) {
echo "<h1>". $value . "</h1>";
}
}
?>
</div>
<form action="registerExec.php" method="post" name="myForm" onsubmit="return(validateEmail());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td align="right">Email</td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td align="right">Retype Email</td>
<td><input type="text" name="reEmail" id="reEmail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
Your PHP to display the form content -
<?php
$email = $_POST['email'];
$zip = $_POST['zip'];
$name = $_POST['name'];
$country = $_REQUEST['country'];
$message = array();
$goodjob = 'goodjob';
if ($email == "" || $zip == "" || $name ==""){
array_push($message, "Email, Zip, Name should not be empty!");
// chedk if any of these fields is empty
}
if ($name != ""){
if (is_numeric($name)) {
array_push($message, "don't include numberss in name");
}
}
if (!is_numeric ($zip)){
array_push($message, "zip is not a number!");
}
if (strlen($zip) != 5){
array_push($message, "Wrong Zip!");
}
if (empty($message)){
array_push($message, $name);
array_push($message, $email);
array_push($message, $zip);
$finalmessage = http_build_query(array('message' => $message));
header("Location: index.php?".$finalmessage);
} else {
$finalmessage = http_build_query(array('message' => $message));
header("Location: index.php?".$finalmessage);
}
?>

Validation for Radio Button

I tried to make a registration form for new user. The form works well if all the values are entered in the field.But i get mysql error for radio button when i directly submit the form.I have also used a feature to check if username already exists or no & match the password.If i have left any field blank & press submit then the page gets blank & user needs to fill in all the details from start & alert for Username already exists come.I want this alert only to be displayed when username is same as in db. Please Help!
<?php session_start();
// define variables and set to empty values
$fname=$gender=$dept=$email=$uname=$pswd=$cpswd=$role="";
$fnameErr=$genderErr=$deptErr=$emailErr=$unameErr=$pswdErr=$cpswdErr=$roleErr="";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["fname"]))
{
$fnameErr = "Name is required";
}
else
{
$fname = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname))
{
$fnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["gender"]))
{
$genderErr = "Gender is required";
}
else
{
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["dept"]))
{
$deptErr = "Department is required";
}
else
{
$dept = test_input($_POST["dept"]);
}
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["uname"]))
{
$unameErr = "Username is required";
}
else
{
$uname = test_input($_POST["uname"]);
}
if (empty($_POST["pswd"]))
{
$pswdErr = "Password is required";
}
else
{
$pswd = test_input($_POST["pswd"]);
}
if (empty($_POST["cpswd"]))
{
$cpswdErr = "Password is required";
}
else
{
$cpswd = test_input($_POST["cpswd"]);
}
if (empty($_POST["role"]))
{
$roleErr = "Role is required";
}
else
{
$role = test_input($_POST["role"]);
}
if (!empty($_POST))
{
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="testmra"; // Database name
// Connect to server and select databse.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect");
mysqli_select_db($conn,$db_name);
$name = mysqli_real_escape_string($conn, $_POST['fname']);
$gender =mysqli_real_escape_string($conn,$_POST['gender']);
$department = mysqli_real_escape_string($conn, $_POST['dept']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$username = mysqli_real_escape_string($conn, $_POST['uname']);
$userpass = mysqli_real_escape_string($conn, $_POST['pswd']);
$cpass = mysqli_real_escape_string($conn, $_POST['cpswd']);
$role= mysqli_real_escape_string($conn, $_POST['role']);
$res=mysqli_query($conn,"SELECT username FROM newuser WHERE username='$username'");
$row=mysqli_fetch_row($res);
if($row>0)
{
echo '<script language="javascript">';
echo 'alert("Username '.$username.' already been selected")';
echo '</script>';
}
elseif($userpass!=$cpass)
{
$cpswdErr="Password doesn't match";
}
else
{
$sql="INSERT INTO newuser (name,gender,department,emailid,username,userpass,role)VALUES('$name','$gender','$department','$email','$username','$userpass','$role')";
if (mysqli_query($conn,$sql))
{
header("location:trialregister.php");
exit();
}
else
{
die('Error: Cannot connect to db' );
}
}
}
}
else { }
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<html>
<head><title>MRA</title></head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table align="center" cellspacing="5" cellpadding="5">
<tr><td align="right">Full Name :</td><td><input type="text" name="fname"></td><td align="left"><font color="red"><?php echo $fnameErr; ?></td></tr>
<tr><td align="right">Gender :</td><td><input type="radio" name="gender" value="Male">Male<input type="radio" name="gender" value="Female">Female</td><td align="left"><font color="red"><?php echo $genderErr; ?></td></tr>
<tr><td align="right">Department :</td><td><select name="dept">
<option value="">Select Department</option>
<option value="IT">IT</option>
<option value="HR">HR</option>
<option value="Accounts">Accounts</option>
<option value="Sales">Sales</option>
</select></td><td align="left"><font color="red"><?php echo $deptErr; ?></td></tr>
<tr><td align="right">EmailId :</td><td><input type="text" name="email"></td><td align="left"><font color="red"><?php echo $emailErr; ?></td></tr>
<tr><td align="right">Username :</td><td><input type="text" name="uname"></td><td align="left"><font color="red"><?php echo $unameErr; ?></td></tr>
<tr><td align="right">Password :</td><td><input type="password" name="pswd"></td><td align="left"><font color="red"><?php echo $pswdErr; ?></td></tr>
<tr><td align="right">Confirm Password :</td><td><input type="password" name="cpswd"></td><td align="left"><font color="red"><?php echo $cpswdErr; ?></td></tr>
<tr><td align="right">Role :</td><td><input type="radio" name="role" value="User">User<input type="radio" name="role" value="Admin">Admin</td><td align="left"><font color="red"><?php echo $roleErr; ?></td></tr>
<tr><td colspan="3" align="center"><input type="submit" name="submit" value="Submit"> <input type="reset" name="reset" value="Reset"> <input type="button" name="cancel" value="Cancel"></td></tr>
</table>
</form>
</body>
</html>
Try this...
I have changed if condition from "if (!empty($_POST))" to "if ($roleErr =="") ".Because if you not select radio button the "$_POST['gender'],$_POST['role']" not present your post
<?php session_start();
// define variables and set to empty values
$fname=$gender=$dept=$email=$uname=$pswd=$cpswd=$role="";
$fnameErr=$genderErr=$deptErr=$emailErr=$unameErr=$pswdErr=$cpswdErr=$roleErr="";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["fname"]))
{
$fnameErr = "Name is required";
}
else
{
$fname = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname))
{
$fnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["gender"]))
{
$genderErr = "Gender is required";
}
else
{
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["dept"]))
{
$deptErr = "Department is required";
}
else
{
$dept = test_input($_POST["dept"]);
}
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["uname"]))
{
$unameErr = "Username is required";
}
else
{
$uname = test_input($_POST["uname"]);
}
if (empty($_POST["pswd"]))
{
$pswdErr = "Password is required";
}
else
{
$pswd = test_input($_POST["pswd"]);
}
if (empty($_POST["cpswd"]))
{
$cpswdErr = "Password is required";
}
else
{
$cpswd = test_input($_POST["cpswd"]);
}
if (empty($_POST["role"]))
{
$roleErr = "Role is required";
}
else
{
$role = test_input($_POST["role"]);
}
if ($roleErr =="")
{
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="testmra"; // Database name
// Connect to server and select databse.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect");
mysqli_select_db($conn,$db_name);
$name = mysqli_real_escape_string($conn, $_POST['fname']);
$gender =mysqli_real_escape_string($conn,$_POST['gender']);
$department = mysqli_real_escape_string($conn, $_POST['dept']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$username = mysqli_real_escape_string($conn, $_POST['uname']);
$userpass = mysqli_real_escape_string($conn, $_POST['pswd']);
$cpass = mysqli_real_escape_string($conn, $_POST['cpswd']);
$role= mysqli_real_escape_string($conn, $_POST['role']);
$res=mysqli_query($conn,"SELECT username FROM newuser WHERE username='$username'");
$row=mysqli_fetch_row($res);
if($row>0)
{
echo '<script language="javascript">';
echo 'alert("Username '.$username.' already been selected")';
echo '</script>';
}
elseif($userpass!=$cpass)
{
$cpswdErr="Password doesn't match";
}
else
{
$sql="INSERT INTO newuser (name,gender,department,emailid,username,userpass,role)VALUES('$name','$gender','$department','$email','$username','$userpass','$role')";
if (mysqli_query($conn,$sql))
{
header("location:trialregister.php");
exit();
}
else
{
die('Error: Cannot connect to db' );
}
}
}
}
else { }
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<html>
<head><title>MRA</title></head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table align="center" cellspacing="5" cellpadding="5">
<tr><td align="right">Full Name :</td><td><input type="text" name="fname"></td><td align="left"><font color="red"><?php echo $fnameErr; ?></td></tr>
<tr><td align="right">Gender :</td><td><input type="radio" name="gender" value="Male">Male<input type="radio" name="gender" value="Female">Female</td><td align="left"><font color="red"><?php echo $genderErr; ?></td></tr>
<tr><td align="right">Department :</td><td><select name="dept">
<option value="">Select Department</option>
<option value="IT">IT</option>
<option value="HR">HR</option>
<option value="Accounts">Accounts</option>
<option value="Sales">Sales</option>
</select></td><td align="left"><font color="red"><?php echo $deptErr; ?></td></tr>
<tr><td align="right">EmailId :</td><td><input type="text" name="email"></td><td align="left"><font color="red"><?php echo $emailErr; ?></td></tr>
<tr><td align="right">Username :</td><td><input type="text" name="uname"></td><td align="left"><font color="red"><?php echo $unameErr; ?></td></tr>
<tr><td align="right">Password :</td><td><input type="password" name="pswd"></td><td align="left"><font color="red"><?php echo $pswdErr; ?></td></tr>
<tr><td align="right">Confirm Password :</td><td><input type="password" name="cpswd"></td><td align="left"><font color="red"><?php echo $cpswdErr; ?></td></tr>
<tr><td align="right">Role :</td><td><input type="radio" name="role" value="User">User<input type="radio" name="role" value="Admin">Admin</td><td align="left"><font color="red"><?php echo $roleErr; ?></td></tr>
<tr><td colspan="3" align="center"><input type="submit" name="submit" value="Submit"> <input type="reset" name="reset" value="Reset"> <input type="button" name="cancel" value="Cancel"></td></tr>
</table>
</form>
</body>
</html>
<form action="" method="post">
Why don't they play poker in the jungle?<br>
<input type="radio" name="jungle" value="treefrog"> Too many tree frogs.<br>
<input type="radio" name="jungle" value="cheetah"> Too many cheetahs.<br>
<input type="radio" name="jungle" value="river"> Too many rivers.<br><br>
Check the box if you want your answer to be graded:
<input type="checkbox" name="grade" value="yes"><br><br>
<input type="submit" name="submit" value="Submit"><br>
</form>

PHP How to submit form, if there are no errors. no javascript

I have separate email script; however, how would we run that code if there are no errors. I have a array with form errors $errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr); but they have different strings, if there are no strings or Null or '' inside the array, we would like to send email.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $phoneErr = $emailErr = $zipErr = $serviceErr = "";
$name = $phone = $email = $zip = $service = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "name required.";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "letters and spaces only.";
}
}
if (empty($_POST["email"])) {
$emailErr = "email 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["phone"])) {
$phoneErr = "phone required.";
} else {
//Check phone for numbers () or - only
$phone = test_input($_POST["phone"]);
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $phone)) {
$phoneErr = "format.";
}
}
if (empty($_POST["zip"])) {
$zipErr = "zip required.";
} else {
$zip = test_input($_POST["zip"]);
}
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $zip)){
$zipErr = "format.";
}
if ($_POST["service"] == NULL ) {
$serviceErr = "service required.";
}else {
$service = test_input($_POST["service"]);
}
$comment = test_input($_POST["comment"]);
//**********************************************************************
$errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr);
if (isset($_POST['Submit'])) {
//if no errors run send email CODE.
}
//***********************************************************************
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td> Name:
<br />
<input name="name" type="text" size="20" value="<?php echo $name;?>">
<span class="error">* <?php echo "<br />"; echo $nameErr;?></span>
</td>
</tr>
<tr>
<td> Phone:
<br />
<input name="phone" type="text" size="20" value="<?php echo $phone;?>">
<span class="error">* <?php echo "<br />"; echo $phoneErr;?></span>
</td>
</tr>
<tr>
<td> E-mail:
<br />
<input name="email" type="text" size="20" value="<?php echo $email;?>">
<span class="error">* <?php echo "<br />"; echo $emailErr;?></span>
</td>
</tr>
<tr>
<td> Zip:
<br />
<input name="zip" type="text" size="20" value="<?php echo $zip;?>">
<span class="error">* <?php echo "<br />"; echo $zipErr;?></span>
</td>
</tr>
<tr>
<td> Service:
<br />
<select name="service">
<option selected="selected" value="<?php echo $service;?>"><?php echo $service;?></option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<span class="error">* <?php echo "<br />"; echo $serviceErr;?></span>
</td>
</tr>
<tr>
<td> Message:
<br />
<textarea name="comment" rows="2" cols="20"><?php echo $comment;?></textarea></td>
</tr>
<tr>
<td>
<input type="submit" name="Submit" value="Send" />
</td>
</tr>
</table>
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $phone;
echo "<br>";
echo $zip;
echo "<br>";
echo $service;
echo "<br>";
echo "$comment";
?>
</body>
</html>
try with the below code:
$errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr);
if (isset($_POST['Submit'])) {
if(!array_filter($errors)){
// code here
}
else {
echo "Error";
}
}
Save your errors in an array, then check if the array is empty at the end. If so, no errors - submit email. Else, display errors:
//dont declare separate variables,use an array
//$nameErr = $phoneErr = $emailErr = $zipErr = $serviceErr = "";
$errors = [];
if (empty($_POST["name"])) {
$errors['nameErr'] = "name required.";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$errors['nameErr'] = "letters and spaces only.";
}
}
//other validation here, then
if(empty($errors){
//no errors, submit
your_submit_function();
}else{
//display errors
foreach($errors as $val){
echo $val . '<br/>';
}
}

PHP/HTML form processing

The assignment is to create an html form where the user enters the required information, and process the form data via PHP to display the output using $_post method. I can't seem to get the output right, it just basically displays the php code that I wrote. any insight is greatly appreciated
Note: The html code is lengthy, but I'm sure it's correct. My problem is with the PHP(next) code.
the following is the output:
0){ $Name = trim($_POST['name']); $adr = trim($_POST['address']); $City = trim($_POST['city']); $state = trim($_POST['state']); $zip = trim($_POST['zip']); $phone = trim($_POST['phone']); $email = trim($_POST['email']); $err = array(); if($Name == ''){ $err[] = "Please enter your name"; } if($adr == ''){ $err[] = "Please enter your address"; } if($City == ''){ $err[] = "Please enter your city"; } if($state == ''){ $err[] = "Please enter your State"; } if($zip == ''){ $err[] = "Please enter your zip"; } if($phone == ''){ $err[] = "Please enter your phone number"; } if($email == ''){ $err[] = "Please enter your email"; } if(count($err) > 0){ foreach($err as $value){ echo"$value
"; } echo " Go Back"; } else{ //header("Location:HTMLform.html"); echo "Name: " . $_POST["name"]; echo "Address: " . $_POST["address"] ; echo "City: " . $_POST["city"] ; echo "State: " . $_POST["state"]; echo "Zip: " . $_POST["zip"]; echo "Phone: " . $_POST["phone"]; echo "Email: " . $_POST["email"]; } } ?>
page 1 (HTML FORM)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Coffee Order</title>
</head>
<body><h1>The Coffee House</h1>
<div>
<div><h3>Order Form</h3></div>
<form name='frmInput' action="process.php" method="post">
<table><tr><td>Coffee:</td>
<td><select name="coffeeCode" id="Coffee">
<option value="">Select Coffee:</option><option value="bv">Boca Villa ($7.99/lb)
</option>
<option value="sbr">South Beach Rhythm ($8.99/lb)</option>
<option value="pp">Pumpkin Paradise ($8.99/lb)</option>
<option value="ss">Sumatran Sunset ($9.99/lb)</option>
<option value="bb">Bali Batur ($10.95/lb)</option>
<option value="dd">Double Dark ($9.95/lb)</option></select></td></tr>
<tr><td>
Type:</td>
<td>
<input type="radio" name="coffeeType" value="caf">Regular<br/>
<input type="radio" name="coffeeType" value="decaf">Decaffeinated
</td>
</tr>
<tr>
<td>Quantity (in pounds):</td>
<td>
<input type="text" name="quantity" maxlength="3" size="3" id="Quantity">
</td>
</tr>
<tr>
<td>Name:</td>
<td>
<input type="text" name="name" id="Name">
</td>
</tr>
<tr>
<td>E-mail address:</td>
<td>
<input type="text" name="email" id="Email">
</td>
</tr>
<tr>
<td>Telephone #:</td>
<td>
<input type="text" name="phone" maxlength="14" size="14" id="Telephone">
</td>
</tr>
<tr>
<td>Address:</td>
<td>
<input type="text" name="address" id="Address">
</td>
</tr>
<tr>
<td>City:</td>
<td>
<input type="text" name="city" id="City">
</td>
</tr>
<tr>
<td>State:</td>
<td>
<input type="text" name="state" maxlength="2" size="2"
style="text-transform: uppercase" id="State">
</td>
</tr>
<tr>
<td>Zip:</td>
<td>
<input type="text" name="zip" maxlength="10" size="10" id="Zip">
</td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td><td><input type="reset"></td>
</tr>
</table>
</form></div></body>
</html>
php code:
<?php
if (count($_POST) > 0){
$Name = trim($_POST['name']);
$adr = trim($_POST['address']);
$City = trim($_POST['city']);
$state = trim($_POST['state']);
$zip = trim($_POST['zip']);
$phone = trim($_POST['phone']);
$email = trim($_POST['email']);
$err = array();
if($Name == ''){
$err[] = "Please enter your name";
}
if($adr == ''){
$err[] = "Please enter your address";
}
if($City == ''){
$err[] = "Please enter your city";
}
if($state == ''){
$err[] = "Please enter your State";
}
if($zip == ''){
$err[] = "Please enter your zip";
}
if($phone == ''){
$err[] = "Please enter your phone number";
}
if($email == ''){
$err[] = "Please enter your email";
}
if(count($err) > 0){
foreach($err as $value){
echo"$value<br/>";
}
echo "<a href='HTMLform.html'> Go Back</a>";
}
else{
//header("Location:HTMLform.html");
echo "Name: " . $_POST["name"];
echo "Address: " . $_POST["address"] ;
echo "City: " . $_POST["city"] ;
echo "State: " . $_POST["state"];
echo "Zip: " . $_POST["zip"];
echo "Phone: " . $_POST["phone"];
echo "Email: " . $_POST["email"];
}
}
?>
You have some errors in your code.
There is a space between <? tag and php in line 1. Remove that
There is no closing curly brace for this , if (count($_POST) > 0) {. Add a closing curly brace before the ending ?> tag.
You have the name field of telephone set to 'phone'.
So find all lines having this
$_POST['telephone']
and change it to
$_POST['phone']
Also, If you want to see the results, comment out
header('Location:HTMLForm.html');
PHP file are saved with .php extension and has an opening of
PHP code should be at the top of the page, before any HTML tag
Instead of using $variable == '' to check if it's empty, use function called empty($variable) that return true if empty
You are doing a redirect in the first line of the else statement, so the rest of the code won't be executed, therefore the echo part will never be reached. Put this header("Location:HTMLform.html"); as the last statement in the else scope
old
// is this suppose to be an array?
$err = array();
if($_POST['name'] == null){
array_push($err,'error stuff stuff stuff');
}
print_r($err);
// if not array
$err = '';
if($_POST['name'] == null){
$err.= 'error stuff stuff stuff';
}
Also, What are you trimming from the post?

Form validation using PHP

I want to validate my form so ALL of the fields are required. If a field is NOT inserted or left blank it will display an error message AFTER submission. Could anyone help?
Form
<html>
<head>
<title>Form Input Data</title>
</head>
<table>
<body><table border="1">
<table bgcolor="lightblue"></body>
<form method="post" action="insert_ac.php">
<br>
<tr><td align="left"><strong>Nurse Information</strong></td></tr>
<tr>
<td><font color="red">Please select your name</font></td>
</tr>
<tr>
<td>Fullname</td>
<td><select name="valuelist">;
<option value="valuelist" name="nurse_name" value='<?php echo $nurse_name; ?>'></option>
<?php
$value=$_POST ["valuelist"];
$con = mysql_connect("localhost","root","") or die('Could not connect:'.mysql_error());
mysql_select_db("a&e", $con) or die('Could not select database.');
$fetch_nurse_name = mysql_query("SELECT DISTINCT Fullname FROM nurse");
while($throw_nurse_name = mysql_fetch_array($fetch_nurse_name)) {
echo '<option value=\"'.$throw_nurse_name[0].'">'.$throw_nurse_name[0].'</option>';
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td>Please register name here:</td>
<tr>
<td>Fullname</td>
<td><input type="text" name="nurse_forename" size="30"> </td>
</tr>
</tr>
I would do something like this:
$req = ['field1', 'field2', 'field...'];
$status = true;
foreach ($req as $field) {
if (empty($_POST[$field])) {
echo 'Field ' . $field . ' is empty';
$status = false;
}
}
if ($status) {
// ok
} else {
// not okay!
}
You create an array ($req), with all field names and loop over them. Check every field against empty() (check the php manual for this function).
Here is a better (and mostly) correct HTML snippet... Please indent properly and read any HTML tutorial for well formed code. Your HTML is **.
<?php
$value=$_POST["valuelist"];
$con = mysql_connect("localhost","root","") or die('Could not connect:'.mysql_error());
mysql_select_db("a&e", $con) or die('Could not select database.');
$fetch_nurse_name = mysql_query("SELECT DISTINCT Fullname FROM nurse");
?>
<html>
<head>
<title>Form Input Data</title>
</head>
<body>
<form method="post" action="insert_ac.php">
<table border="1" bgcolor="lightblue">
<tr>
<td align="left"><strong>Nurse Information</strong></td>
</tr>
<tr>
<td><font color="red">Please select your name</font></td>
</tr>
<tr>
<td>Fullname</td>
<td>
<select name="valuelist">
<option value="valuelist" value="<?php echo $nurse_name; ?>"></option>
<?php
while($throw_nurse_name = mysql_fetch_array($fetch_nurse_name)) {
echo '<option value="'.$throw_nurse_name[0].'">'.$throw_nurse_name[0].'</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td>Please register name here:</td>
</tr>
<tr>
<td>Fullname</td>
<td><input type="text" name="nurse_forename" size="30"> </td>
</tr>
</table>
</form>
</body>
</html>
If you have only the two given fields, this would do it:
$status = false;
$name = '';
if (!empty($_POST['nurse_forename'])) {
$name = $_POST['nurse_forename'];
$status = true;
} elseif (!empty($_POST['valuelist'])) {
$name = $_POST['valuelist'];
$status = true;
} else {
$status = false;
// none of nurse_forname OR valuelist is filled
// abort.
}
Something like
foreach($_POST as $form_entry)
if(empty($form_entry))
echo 'you have to fill in all fields';
if (isset($_POST['variable']{0})) {
echo 'I exist and I have at least one char!';
else
echo 'I dont exist or I have no chars!';
It checks whether $_POST['variable'] exists and has at least one char.
if($_POST['valuelist'] == NULL or $_POST['nurse_forename'] == NULL){
die('empty');
}
Untested.
Try it this way:
if(empty($_POST['nurse_forename'])){
echo "Field Nurse-Forename is empty";
}
You also could check like this:
if($_POST['nurse_forename']==""){
echo "Nurse-Forename is empty";
}
You cannot check for all fields with one command (because you cannot distinct between one and more empty fields). You could do it a little more elegant using OOP, but I think for the code you posted above the example should do.
Also You can try this, It's validating all form items.
if (isset ( $_POST ['submit_button_name'] )) {
$validated = true;
array_walk_recursive ( $_POST, function ($value, $key) {
global $validated;
if (! trim ( $value ))
$validated = false;
} );
if ($validated) {
// insert function and redirect
} else {
// print Your message
}
}
// Your form
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);}
if (empty($_POST["website"]))
{$website = "";}
else
{$website = test_input($_POST["website"]);}
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"]);}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>

Categories