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.
Related
I am creating a php form for data validation but there are some errors that I can't find.
When I submit the form the required notification is displayed. But when I reload the page then the required notification still remains. My code is:
<!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"]);
// 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"]);
}
}
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" 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
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?>
value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
This is the result when I first type the address in the browser.
This is the result when I enter an empty value in all the fields and submit the form. This will remain when I reload the page and until I close the browser tab and open a new tab and enter the url again.
You got error message when you reload after form submission. Try following code into your JS file or in JS code.
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
Hope this will help you!
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>
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/>';
}
}
I'm using this code from W3 (http://www.w3schools.com/php/php_form_complete.asp) to make server side validation for given example 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"]);
// 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 syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$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"]);
}
}
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" 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>
<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>
Although server side validation works fine,I can't put mail() function to work ONLY WHEN both $name (treated as subject) and $comment (treated as message) fields are filled.
I've tried many combinations but email is always submitted even when fields are empty.
So my question is: how to make this validated form send email only when $name and $comment fields are filled and validated?
As you are creating $nameErr when the name is invalid and $comment is an empty string when the comment is valid you can use the following conditional:
if (!$nameErr && $comment) {
}
Empty strings are considered FALSE:
http://php.net/manual/en/language.types.boolean.php
You can always use flags.
<?php
....
// let's say there are some flags for validation
if($flag1 && $flag2 && .. $flagN){
// perform email sending here
}
?>
Or you can use the default error message variables; check if they are empty
<?php
if(!empty($nameErr) && !empty($comment)){
// perform email sending
}
?>
Do the validation after you validated $name and $comment:
if($nameErr == "" && $emailErr == "") { // If they are empty, no errors where found
// Do your email validation here
}
I'm trying to do form validation and storing the validated data in mysql database using php.The code works fine as its supposed to do save the form data in mysql db after the validation process.The problem is it shows the undefined index error in these lines
1.<span class="error">* <?php echo $error['name'];?></span>
2.<span class="error">* <?php echo $error['email']; ?></span>
3.<span class="error"><?php echo $error['website']; ?></span>
4.<span class="error">* <?php echo $error['gender'];?></span>.
here is my full code.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$error=array();
$name = $email = $gender = $comment = $website = $data = "";
function test_input($data)
{
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$error['name']= "Name is required";}
else
{
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$error['name'] = "Only letters and white space allowed";
}
}
if (empty($_POST["email"]))
{$error['email'] = "Email is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$error['email'] = "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))
{
$error['website'] = "Invalid URL";
}
}
if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
if (empty($_POST["gender"]))
{$error['gender'] = "Gender is required";}
else
{$gender = test_input($_POST["gender"]);}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $error['name'];?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $error['email']; ?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $error['website']; ?></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 $error['gender'];?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
$con=mysqli_connect("localhost","root","root","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO np_appoint (Name,Email,Website,Comment,Gender)
VALUES
('$_POST[Name]','$_POST[Email]','$_POST[website]','$_POST[Comments]','$_POST[Gender]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
</body>
</html>
To avoid undefined values use isset().
<span class="error"> <?php if(isset($error['name']))
echo $error['name'];?></span>
Its because if there is no error the $error array is not defined.
try defining the wariables at the beginning of your code>
$error['name'] = '';
$error['email'] = '';
$error['website'] = '';
$error['gender'] = '';
Your error messages are set one at a time, but the keys in $error array are not predefined. So if name is valid you will not have $error['name']. This will produce a undefined index NOTICE.
USe isset() function
<span class="error">* <?php if(isset($error['name']))
echo $error['name'];?></span>
Or error supressing using # (not recommended )
<span class="error">* <?php echo #$error['name'];?></span>
Attempting to access an array key which has not been defined is the same as accessing any other undefined variable gives an E_NOTICE-level error message like undefined index
Try this, count($error)>0
<?php if(count($error)>0){?>
<span class="error">* <?php echo $error['name'];?></span>
<?php } ?>
OR
You can use foreach
<?php foreach($error as $value){?>
<span class="error">* <?php echo $value;?></span>
<?php } ?>