Validation for Radio Button - php

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>

Related

Using Parameterized Queries/Prepared Statements

I'm new to php coding and have been told by others that I need to be using parameterized queries/prepared statements for my php scripts and MySQL database. I've looked at other examples of scripting these prepared statements and they usually refer to user login functions. My query is just a web form to capture user inputted data and store in database (SQL insert as opposed to SQL select). I am hoping someone can help me with how to script the php to prevent sql injections. Also hoping someone can let me know whether these prepared statements should also be used in php SQL Select scripts where I am only displaying database records on a form. Thanks in advance!
Here are the two php files I am using, the first is my database connection script:
<?php
DEFINE ('DB_USER', 'fakeuser');
DEFINE ("DB_PSWD", 'fakepassword');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'newspaper');
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
?>
Web form PHP script:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$errors = "false";
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {
$nameErr = "Name is required";
$errors = "true";
} else {
$name = test_input($_POST["Name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
$errors = "true";
}
}
if (empty($_POST["Email"])) {
$emailErr = "Email is required";
$errors = "true";
} 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";
$errors = "true";
}
}
if (empty($_POST["Website"])) {
$website = "";
} else {
$website = test_input($_POST["Website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["Comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["Comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
$errors = "true";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["Subscription"])) {
$subErr = "Subscription is required";
$errors = "true";
}
else {
$sub = test_input($_POST["Subscription"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>
<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Newspaper Subscription Request</legend>
Name: <input type="text" name="Name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="Email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="Website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="Comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Subscription:
<select name="Subscription">
<option value=""></option>
<option value="Daily">Daily</option>
<option value="Evening">Evening</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
</select>
<span class="error">* <?php echo $subErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
Visit Admin Page
</fieldset>
</form>
<?php
if (isset($_POST['submitted']) && $errors == "false")
{
include('connect-mysql.php');
$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO subscriptions (Name, Email, Comment, Subscription) VALUES ('$fname',
'$femail', '$fcomment', '$fsubsciption')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die(mysqli_error($dbcon)); //and die('error inserting new record') ;
} // end of nested if statement
// else
$newrecord = "1 record added to the database";
} // end of main if statement
?>
<?php
echo $newrecord
?>
</body>
</html>
UPDATED CODE with Prepared Statement 9/3/17: See bottom of script (Please tell me if you see any issues with this) Also I've commented out the !mysqli_query IF statement below the prepared statement as I thought this was now redundent, but please tell me if it is still required.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$errors = "false";
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {
$nameErr = "Name is required";
$errors = "true";
} else {
$name = test_input($_POST["Name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
$errors = "true";
}
}
if (empty($_POST["Email"])) {
$emailErr = "Email is required";
$errors = "true";
} 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";
$errors = "true";
}
}
if (empty($_POST["Website"])) {
$website = "";
} else {
$website = test_input($_POST["Website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["Comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["Comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
$errors = "true";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["Subscription"])) {
$subErr = "Subscription is required";
$errors = "true";
}
else {
$sub = test_input($_POST["Subscription"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>
<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Newspaper Subscription Request</legend>
Name: <input type="text" name="Name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="Email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="Website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="Comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Subscription:
<select name="Subscription">
<option value=""></option>
<option value="Daily">Daily</option>
<option value="Evening">Evening</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
</select>
<span class="error">* <?php echo $subErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
Visit Admin Page
</fieldset>
</form>
<?php
if (isset($_POST['submitted']) && $errors == "false")
{
include('connect-mysql.php');
$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO subscriptions (Name, Email, Comment, Subscription) VALUES (?,?,?,?)";
$stmt = mysqli_stmt_init($dbcon);
if (!mysqli_stmt_prepare($stmt,$sqlinsert)) {
echo "SQL error"; }
else {
mysqli_stmt_bind_param($stmt,"ssss",$fname, $femail, $fcomment, $fsubsciption);
mysqli_stmt_execute($stmt);
echo '1 record added to the database';
//if (!mysqli_query($dbcon, $sqlinsert)) {
//die(mysqli_error($dbcon));
} // end of nested IF statement
// else
//$newrecord = "1 record added to the database";
} // end of main if statement
?>
<?php
echo $newrecord
?>
</body>
</html>

Defined Variable in PHP script has undefined variable error

I'm recieving an issue in the following php code. I am recieiving an unknown variable error in line 146, (echo $newrecord) variable. I'm not sure what is wrong with this variable, I have defined it in the IF statement, and am simply echoing if it is successful. I originally had that segment of code (after ) at the top of the script, but it was causing issues with the mandatory field error messages displaying properly. Any help is appreciated!
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["Name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
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["Website"])) {
$website = "";
} else {
$website = test_input($_POST["Website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
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"]);
}
if (empty($_POST["Subscription"])) {
$subErr = "Subscription is required"; }
else {
$sub = test_input($_POST["Subscription"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>
<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Newspaper Subscription Request</legend>
Name: <input type="text" name="Name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="Email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="Website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="Comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Subscription:
<select name="Subscription">
<option value=""></option>
<option value="Daily">Daily</option>
<option value="Evening">Evening</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
</select>
<span class="error">* <?php echo $subErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
Visit Admin Page
</fieldset>
</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;
echo "<br>";
echo $sub;
?>
<?php
if (isset($_POST['submitted'])) {
include('connect-mysql.php');
$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO newspaper (Name, Email, Comment, Subscription) VALUES ('$fname',
'$femail', '$fcomment', '$fsubsciption')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} // end of nested if statement
$newrecord = "1 record added to the database";
} // end of main if statement
?>
<?php
echo $newrecord
?>
</body>
</html>
newrecord is defined and initialized inside the if statement, therefore if your code opts to the else, it will skip the if and your newrecord variable won't exist.
$newrecord is defined within an if statement, when the if is not executed the variable is not available. You can define it by default adding $newrecord = ''; before you start the if for the submit.

How to validate forms when everytime action is on same page

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>

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/>';
}
}

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