I'm receiving an undefined index erroron one line of my code. I've double checked the spelling and verified it's also correctly identified in my database. I even swapped out another section of code that doesn't generate an error and changed the variable to no effect. The variable in question is FinalReviewDate.
<h2>Project Updates</h2>
<p class="first"></p>
<form action="http://www.oldgamer60.com/Project/Update.php" method="post">
<div class="fieldset">
<fieldset>
Project: <input type="text" name="Project" value="<?php if(isset($Project)){ echo $Project; } ?>">
<br><br>
Client: <input type="text" name="Client" value="<?php if(isset($Client)){ echo $Client; } ?>">
<br><br>
Date Received: <input type="text" name="DateReceived" value="<?php if(isset($DateReceived)){ echo $DateReceived; } ?>">
<br><br>
Last Name: <input type="text" name="LastName" value="<?php if(isset($LastName)){ echo $LastName; } ?>">
<br><br>
Final Review Date: <input type="text" name="FinalReviewDate value="<?php if(isset($FinalReviewDate)){ echo $FinalReviewDate; } ?>">
<br><br>
Date Delivered: <input type="text" name="DateDelivered" value="<?php if(isset($DateDelivered)){ echo $DateDelivered; } ?>">
<br><br>
Date Accepted: <input type="text" name="DateAccepted" value="<?php if(isset($DateAccepted)){ echo $DateAccepted; } ?>">
<br><br>
<input type="submit" name="submit" value="Submit">
</fieldset>
</div>
</form>
<br>
<?php
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST['submit']) && !$connection->connect_error){
// to track errors
$error = false;
// now validate input fields
if(!preg_match("/^[a-zA-Z\s]{1,}$/",$_POST['Project'])){
// check if project only contains letters and whitespace
$ProjectErr = "Only letters and white space allowed";
$error = true;
}else{
$Project = test_input($_POST['Project']);
}
if(!preg_match("/^[a-zA-Z\s]{1,}$/",$_POST['Client'])){
// check if client only contains letters and whitespace
$ClientErr = "Only letters, numbers and white space allowed";
$error = true;
}else{
$Client = test_input($_POST['Client']);
}
if(!preg_match("/^[a-zA-Z\s]{1,}$/",$_POST['DateReceived'])){
// check if last name only contains letters and whitespace
$DateReceivedErr = "Only letters and white space allowed";
$error = true;
}else{
$DateReceived = test_input($_POST['DateReceived']);
}
if(!preg_match("/^[a-zA-Z\s]{1,}$/",$_POST['LastName'])){
// check if data received only contains letters and whitespace
$LastNameErr = "Only letters and white space allowed";
$error = true;
}else{
$LastName = test_input($_POST['LastName']);
}
if(!preg_match("/^[0-9]{1}-[0-9]{3}-[0-9]{3}-[0-9]{4}$/",$_POST['FinalReviewDate'])){
// check if data received only contains letters and whitespace
$FinalReviewDateErr = "Only letters and white space allowed";
$error = true;
}else{
$FinalReviewDate = test_input($_POST['FinalReviewDate']);
}
if(!preg_match("/^[0-9]{1}-[0-9]{3}-[0-9]{3}-[0-9]{4}$/",$_POST['DateDelivered'])){
// check if data received only contains letters and whitespace
$DateDeliveredErr = "Only letters and white space allowed";
$error = true;
}else{
$DateDelivered = test_input($_POST['DateDelivered']);
}
if(!preg_match("/^[0-9]{1}-[0-9]{3}-[0-9]{3}-[0-9]{4}$/",$_POST['DateAccepted'])){
// check if data received only contains letters and whitespace
$DateAcceptedErr = "Only letters and white space allowed";
$error = true;
}else{
$DateAccepted = test_input($_POST['DateAccepted']);
}
//set var field to update
if(!$error){
$query = "UPDATE `Projects` SET `Project`=[value-1],`Client`=[value-2],`DateReceived`=[value-3],`LastName`=[value-4],`FinalReviewDate`=[value-5],`DateDelivered`=[value-6],`DateAccepted`=[value-7] WHERE Project = '$Project'";
if($connection->query($query)){
echo "record is successfully updated!";
}else{
echo "error: record could not be updated";
}
}
}
?>
<?php
$connection->close();
?>
Forget to close name attribute
<input type="text" name="FinalReviewDate" value="<?php if(isset($FinalReviewDate)){ echo $FinalReviewDate; } ?>">
^
Related
My form inputs records if I format the form fields according to the regex I have established and then echo's the record being inserted into the database successfully. If I make any errors, it simply erases the fields and doesn't echo the error. I'm fairly new to php and I'm doing this for a class project as part of an online course. I'm not sure where my error is. Any help will be greatly appreciated.
<!DOCTYPE HTML>
<html lang = "en">
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Tech Order Department.html</title>
<meta charset = "UTF-8" />
<style>
div {
text-align: justify;
}
.section {
margin-left: auto;
margin-right: auto;
width: 70%;
}
</style>
</head>
<body>
<h2>Tech Orders</h2>
<br>
<title>Page Title</title>
<h2>New Project</h2>
<p class="first"><span class="error">* required field.</span></p>
<form action="http://www.oldgamer60.com/Project/try.php" method="post">
<div class="fieldset">
<fieldset>
Project: <input type="text" name="Project" value="<?php if(isset($Project)){ echo $Project; } ?>">
<span class="error">* <?php if(isset($ProjectErr)){ echo $ProjectErr; } ?></span>
<br><br>
Client: <input type="text" name="Client" value="<?php if(isset($Client)){ echo $Client; } ?>">
<span class="error">* <?php if(isset($ClientErr)){ echo $ClientErr; } ?></span>
<br><br>
LastName: <input type="text" name="LastName" value="<?php if(isset($LastName)){ echo $LastName; } ?>">
<span class="error">* <?php if(isset($LastNameErr)){ echo $LastNameErr; } ?></span>
<br><br>
DateReceived: <input type="text" name="DateReceived" value="<?php if(isset($DateReceived)){ echo $DateReceived; } ?>">
<span class="error">* <?php if(isset($DateReceivedErr)){ echo $DateReceivedErr; } ?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</fieldset>
</div>
</form>
<br>
<?php
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST['submit']) && !$connection->connect_error){
// to track errors
$error = false;
// now validate input fields
if (empty($_POST['Project']) || !isset($_POST['Project'])){
$ProjectErr = "Project name is required";
$error = true;
}elseif(!preg_match("/^[A-Za-z0-9.-]+$/",$_POST['Project'])){
// check if project only contains number, letters, comma's periods and whitespace
$ProjectErr = "Only letters, numbers, comma's, periods and white space allowed";
$error = true;
}else{
$Project = test_input($_POST['Project']);
}
if (empty($_POST['Client']) || !isset($_POST['Client'])){
$ClientErr = "Client name is required";
$error = true;
}elseif(!preg_match("/^[A-Za-z0-9.-]+$/",$_POST['Client'])){
// check if project only contains number, letters, comma's periods and whitespace
$ClientErr = "Only letters, numbers, comma's, periods and white space allowed";
$error = true;
}else{
$Client = test_input($_POST['Client']);
}
if (empty($_POST['LastName']) || !isset($_POST['LastName'])){
$LastNameErr = "Last name is required";
$error = true;
}elseif(!preg_match("/^[A-Za-z0-9-]+$/",$_POST['LastName'])){
// check if last name only contains letters and whitespace
$LastNameErr = "Only letters and white space allowed";
$error = true;
}else{
$LastName = test_input($_POST['LastName']);
}
if (empty($_POST['DateReceived']) || !isset($_POST['DateReceived'])){
$DateReceivedErr = "Data received field is required";
$error = true;
}elseif(!preg_match("/^\d{4}-\d{2}-\d{2}$/",$_POST['DateReceived'])){
// check if data received only contains letters and whitespace
$DateReceivedErr = "Date must be entered as YYYY/MM/DD";
$error = true;
}else{
$DateReceived = test_input($_POST['DateReceived']);
}
if(!$error){
$query = "INSERT INTO Projects (Project, Client, LastName, DateReceived) VALUES ('$Project', '$Client', '$LastName', '$DateReceived')";
if($connection->query($query)){
echo "record is successfully inserted!";
}else{
echo "error: record could not be inserted";
}
}
}
?>
<?php
$connection->close();
?>
</div>
</div>
</body>
</html>
Check this out. In your form you use vars that are not yet defined (Tey are defined down in the code but yout trying to echo them before defining them):
Project: <input type="text" name="Project" value="<?php if(isset($Project)){ echo $Project; } ?>">
<span class="error">* <?php if(isset($ProjectErr)){ echo $ProjectErr; } ?></span>
<br><br>
isset($ProjectErr) is never set since you setting it lower in code and also
$ProjectErr do not exist in your form
Solution, put form down under the php code where you checking input fields.
Edit:
Try something like this:
<!DOCTYPE HTML>
<html lang = "en">
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Tech Order Department.html</title>
<meta charset = "UTF-8" />
<style>
div {
text-align: justify;
}
.section {
margin-left: auto;
margin-right: auto;
width: 70%;
}
</style>
</head>
<body>
<h2>Tech Orders</h2>
<br>
<title>Page Title</title>
<h2>New Project</h2>
<p class="first"><span class="error">* required field.</span></p>
<?php
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST['submit']) && !$connection->connect_error){
// to track errors
$error = false;
// now validate input fields
if (empty($_POST['Project']) || !isset($_POST['Project'])){
$ProjectErr = "Project name is required";
$error = true;
}elseif(!preg_match("/^[A-Za-z0-9.-]+$/",$_POST['Project'])){
// check if project only contains number, letters, comma's periods and whitespace
$ProjectErr = "Only letters, numbers, comma's, periods and white space allowed";
$error = true;
}else{
$Project = test_input($_POST['Project']);
}
if (empty($_POST['Client']) || !isset($_POST['Client'])){
$ClientErr = "Client name is required";
$error = true;
}elseif(!preg_match("/^[A-Za-z0-9.-]+$/",$_POST['Client'])){
// check if project only contains number, letters, comma's periods and whitespace
$ClientErr = "Only letters, numbers, comma's, periods and white space allowed";
$error = true;
}else{
$Client = test_input($_POST['Client']);
}
if (empty($_POST['LastName']) || !isset($_POST['LastName'])){
$LastNameErr = "Last name is required";
$error = true;
}elseif(!preg_match("/^[A-Za-z0-9-]+$/",$_POST['LastName'])){
// check if last name only contains letters and whitespace
$LastNameErr = "Only letters and white space allowed";
$error = true;
}else{
$LastName = test_input($_POST['LastName']);
}
if (empty($_POST['DateReceived']) || !isset($_POST['DateReceived'])){
$DateReceivedErr = "Data received field is required";
$error = true;
}elseif(!preg_match("/^\d{4}-\d{2}-\d{2}$/",$_POST['DateReceived'])){
// check if data received only contains letters and whitespace
$DateReceivedErr = "Date must be entered as YYYY/MM/DD";
$error = true;
}else{
$DateReceived = test_input($_POST['DateReceived']);
}
if(!$error){
$query = "INSERT INTO Projects (Project, Client, LastName, DateReceived) VALUES ('$Project', '$Client', '$LastName', '$DateReceived')";
if($connection->query($query)){
echo "record is successfully inserted!";
}else{
echo "error: record could not be inserted";
}
}
}
?>
<?php
$connection->close();
?>
<form action="http://www.oldgamer60.com/Project/try.php" method="post">
<div class="fieldset">
<fieldset>
Project: <input type="text" name="Project" value="<?php if(isset($Project)){ echo $Project; } ?>">
<span class="error">* <?php if(isset($ProjectErr)){ echo $ProjectErr; } ?></span>
<br><br>
Client: <input type="text" name="Client" value="<?php if(isset($Client)){ echo $Client; } ?>">
<span class="error">* <?php if(isset($ClientErr)){ echo $ClientErr; } ?></span>
<br><br>
LastName: <input type="text" name="LastName" value="<?php if(isset($LastName)){ echo $LastName; } ?>">
<span class="error">* <?php if(isset($LastNameErr)){ echo $LastNameErr; } ?></span>
<br><br>
DateReceived: <input type="text" name="DateReceived" value="<?php if(isset($DateReceived)){ echo $DateReceived; } ?>">
<span class="error">* <?php if(isset($DateReceivedErr)){ echo $DateReceivedErr; } ?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</fieldset>
</div>
</form>
<br>
</div>
</div>
</body>
</html>
I am trying to validate a form field (to be used for First Name) for letters and dashes only, but regardless of how I implement the code, the value of $player_name is still being set.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["player_name"])) {
$nameErr = "Name is required";
} else {
$player_name = test_input($_POST["player_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z -]+$/",$player_name)) {
$nameErr = "Only letters and white space allowed";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
The form has been implemented using the following code:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Registration Date: <input type="text" name="date_captured" id="date_captured" value="<?php echo $current_date; ?>">
<br><br>
Name: <input type="text" name="player_name" id="player_name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $date_captured;
echo $player_name;
echo "<br>";
?>
Even though the "Only letter and white space allowed" error is set and displayed, the value of $player_name is still set.
I fixed it using the following:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fieldTitle = "Player Name";
if (empty($_POST["player_name"])) {
$player_nameErr = $fieldTitle . $requiredErrorText;
} else {
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z -]*$/",test_input($_POST["player_name"]))) {
$player_nameErr = $nameValidationErrorText;
} else {
$player_name = test_input($_POST["player_name"]);
}
}
I'm just starting off with PHP and I've been trying to validate an HTML form and then POST the form's data onto another page, for some reason this doesn't seem to want to work. The issue is that when submit is clicked the page simply refreshes if there are no errors. Here are snippets of the code:
<?php
$nameErr = $surnameErr = " ";
$name = $surname = " ";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$valid = 0;
if (empty($_POST["name"])) {
$nameErr = "Name is required";
$valid++;
} 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["surname"])) {
$surnameErr = "Surname is required";
$valid++;
} else {
$surname = test_input($_POST["surname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "Only letters and white space allowed";
}
}
if($valid == 0){
header('LOCATION: page2.php');
exit();
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
And here is the HTML
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
<div class="label1">
<label>First Name</label>
<input type="text" name="name" id="name" placeholder="John" value="<?php echo $name;?>" onblur="validateName('name')">
<label>Surname</label>
<input type="text" name="surname" id="surname" placeholder="Smith" value="<?php echo $surname;?>" onblur="validateSurname('surname')"> <br />
<input type="submit" name="submit" value="Submit">
</div>
</form>
page2.php
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your surname is: <?php echo $_POST["surname"]; ?>
</body>
</html>
When you do your header('LOCATION: page2.php'); you will loose all your posted data, that will not be available in page2.php.
There are several solutions to that, for example:
use include instead of a header redirect;
store the posted data in a session or a database so that it is available in other pages.
I don't see any reason why you could not use an include here, is there a specific reason you want to redirect?
Try this
**main page**
<form method="post" action="page2.php">
<div class="label1">
<label>First Name</label>
<input type="text" name="name" id="name" placeholder="John" onblur="validateName('name')">
<label>Surname</label>
<input type="text" name="surname" id="surname" placeholder="Smith" onblur="validateSurname('surname')"> <br />
<input type="submit" name="submit" value="submit">
</div>
</form>
**page2.php**
<?php
if (isset($_POST['submit'])) {
$valid = 0;
if (empty($_POST["name"])) {
$name = "Name is required";
$valid++;
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name = "Only letters and white space allowed";
}
else{$name=$_POST["name"];}
}
if (empty($_POST["surname"])) {
$surname = "Surname is required";
$valid++;
} else {
$surname = test_input($_POST["surname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surname = "Only letters and white space allowed";
} else{$surname=$_POST["surname"];}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<html>
<body>
Welcome <?=$name?><br>
Your surname is: <?=$surname?>
</body>
</html>
I am trying to process a form which will insert data into database, but it is inserting anything in database. I am trying this since couple of days...but got no solution....it is also not showing any error also..please guide....asap...
<?php
if(isset($_POST['submit'])){
$generic_drug_name = $_POST['generic_drug_name'];
$brand_drug_name = $_POST['brand_drug_name'];
$manufacturer_name = $_POST['manufacturer_name'];
$type = $_POST['type'];
$price = $_POST['price'];
}else{
$generic_drug_name = '';
$brand_drug_name = '';
$manufacturer_name = '';
$type = '';
$price = '';
}
$errors = '';
$errors['generic_drug_nameErr'] = '';
$errors['brand_drug_nameErr'] = '';
$errors['manufacturer_nameErr'] = '';
$errors['typeErr'] = '';
$errors['priceErr'] = '';
?>
<body>
<header>
<?php echo navigation(); ?>
</header>
<section>
<div id="envelope">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["generic_drug_name"])) {
$errors['generic_drug_nameErr'] = "Name is required";
}else{
$generic_drug_name = test_input($_POST["generic_drug_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$generic_drug_name)) {
$errors['generic_drug_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["brand_drug_name"])) {
$errors['brand_drug_nameErr'] = "Name is required";
}else{
$brand_drug_name = test_input($_POST["brand_drug_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$brand_drug_name)) {
$errors['brand_drug_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["manufacturer_name"])) {
$errors['manufacturer_nameErr'] = "Name is required";
}else{
$manufacturer_name = test_input($_POST["manufacturer_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$manufacturer_name)) {
$errors['manufacturer_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["type"])) {
$errors['typeErr'] = "Type is required";
} else {
$type = test_input($_POST["type"]);
// check if e-mail address is well-formed
if (!preg_match("/^[a-zA-Z ]*$/",$type)) {
$errors['typeErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["price"])) {
$errors['priceErr'] = "";
} else {
$price = test_input($_POST["price"]);
// check if e-mail address is well-formed
if (!preg_match("/^[0-9\_]{1,4}/",$price)) {
$errors['priceErr'] = "Invalid price format";
}
}
}
?>
<center><h1>Add a new brand drug</h1></center><br>
<label>Generic Drug Name</label><span class="error">* </span><span class="text"><?php echo $errors['generic_drug_nameErr'];?></span>
<input type="text" name="generic_drug_name" placeholder="Enter Generic drug Names" value="<?php echo htmlspecialchars($generic_drug_name); ?>" width="100px;"/>
<label>Brand Drug Name</label><span class="error">* </span><span class="text"><?php echo $errors['brand_drug_nameErr'];?></span>
<input type="text" name="brand_drug_name" placeholder="Amlokind" autofocus="autofocus" value="<?php echo htmlspecialchars($brand_drug_name); ?>" width="100px;">
<label>Manufacturer</label><span class="error">* </span><span class="text"><?php echo $errors['manufacturer_nameErr'];?></span>
<input type="text" name="manufacturer_name" placeholder="Glaxo Smithkline Pharmaceuticals Pvt. Ltd." autofocus="autofocus" value="<?php echo htmlspecialchars($manufacturer_name); ?>">
<label>Type</label><span class="error">* </span><span class="text"><?php echo $errors['typeErr'];?></span>
<input type="text" name="type" placeholder="Tablet" autofocus="autofocus" value="<?php echo htmlspecialchars($type); ?>">
<label>Price</label><span class="error">* </span><span class="text"><?php echo $errors['priceErr'];?></span>
<input type="text" name="price" placeholder="10.45" autofocus="autofocus" value="<?php echo htmlspecialchars($price); ?>" >
<input type="submit" name = "submit" value="Add" id="submit"/>
</form>
</div>
<?php
if(isset($_POST['submit'])){
/*$generic_drug_name = $_POST['generic_drug_name'];
$brand_drug_name = $_POST['brand_drug_name'];
$manufacturer_name = $_POST['manufacturer_name'];
$type = $_POST['type'];
$price = $_POST['price'];*/
if(empty($errors)){
$safe_generic_drug_name = strtoupper($generic_drug_name);
$safe_brand_drug_name = strtoupper($brand_drug_name);
$safe_manufacturer_name = ucwords($manufacturer_name);
$safe_type = ucfirst($type);
$safe_price = $price;
$query = "INSERT INTO brand_generic.brand_drug (drug_id, brand_drug_name, manufacturer, type, price)
SELECT id, '{$safe_brand_drug_name}','{$safe_manufacturer_name}', '{$safe_type}', {$safe_price}
FROM brand_generic.generic_drug
WHERE generic_drug_name = '{$safe_generic_drug_name}';";
//INSERT INTO brand_generic.brand_drug (drug_id, brand_drug_name, manufacturer, type, price) VALUES ((SELECT id FROM brand_generic.generic_drug WHERE generic_drug_name = 'AMLODIPINE'), 'ZODIPINE', 'Zorex Pharma Pvt Ltd', 'Tablet', 10);
if(!$query){
die(mysqli_error());
}
$result = mysqli_query($connection, $query);
var_dump($result);
if($result){
$_SESSION["message"] = "Successfully subject created";
//redirect_to("manage_content.php");
echo $_SESSION["message"];
}else{
$_SESSION["message"] = "Sorry, subject couldn't be created";
//redirect_to("new_subject.php");
echo $_SESSION["message"];
}
}
}
?>
This code is also not showing any error....so that's why I can't tell you what's wrong here......but it's not working...that's all I can say right now....Thank You...:)
Hello everyone once again, thanks for your suggestion, but it didn't work for me....but when I put
if(!empty($errors)){
instead of
if(empty($errors)){
it works....it should not work, right?...because it will take any data and insert it into database..if not please guide me....Thank you to all...:)
You cant use set a session after starting printing to browser.
so move
if(isset($_POST['submit'])){
to the top of page, before the HTML.
It shows a debug error message like follows.
Fatal error: Call to undefined function navigation() in /var/www/poc.php on line 25
It mean the function navigation() is used but not created any where in the script. And fatal error won't let the script to further proceed. So it is a blocking point
At least include following line at top of PHP block will avoid the error
<?php
function navigation(){
return 1;
}
?>
Additionally if you want to see the error message on your server use following two lines on the top of the script.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
My php self-validating form is submitting to sql database whether the characters entered into form fields are appropriate or not...How do stop it from submitting until the conditions for each form field are met?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>RSG Contact Us</title>
<script>
// $(function () {
// $('form').on('submit', function (e) {
// $.ajax({
// type: 'post',
// url: 'contact.php',
// data: $('form').serialize(),
// success: function () {
// alert('Thank you! your form has been submitted');
// }
// });
// e.preventDefault();
// });
// });
</script>
</head>
<body>
<div id="contactuscall">
<?php
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$firstnameErr = $lastnameErr = $emailErr = $cellphoneErr = $genDerErr = $dognameErr = $BreedErr = $reasonErr = "";
$firstname = $lastname = $email = $cellphone = $genDer = $dogname = $Breed = $reasoN= $freecomments = "";
//if conditional statement stops PHP from looking for variable values until the submit button is hit
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// check if a first name was provided
if (empty($_POST["firstname"]))
{$firstnameErr = "A first name is required";}
else
{
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
{$firstnameErr = "Only letters and white space allowed";}
}
//check if a last name was provided
if (empty($_POST["lastname"]))
{$lastnameErr = "A last name is required";}
else
{
$lastname = test_input($_POST["lastname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname))
{
$lastnameErr = "Only letters and white space allowed";
}
}
// check if an email was provided
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["cellphone"]))
{$cellphoneErr = "Please provide a phone number";}
else {
$cellphone = test_input($_POST["cellphone"]);
// Regular Expression to allow only valid phone number formats, including numbers, spaces, dashes, extensions
if (!preg_match("/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/",$cellphone))
{$cellphoneErr = "Invalid format";}
}
if (empty($_POST["dogname"]))
{$dognameErr = "A doggy name is required";}
else {
$dogname = test_input($_POST["dogname"]);
// check if dogname only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$dogname))
{$dognameErr = "Only letters and white space allowed";}
}
if (empty($_POST["Breed"]))
{$BreedErr = "A breed name is required";}
else {
$Breed = test_input($_POST["Breed"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Breed))
{$BreedErr = "Only letters and white space allowed";}
}
if(empty($_POST['genDer']))
{$genDerErr= "You forgot to select a Gender!";}
else {
$genDer=($_POST['genDer']);
}
//make sure one of the services requested checkboxes are checked
$reasoN = $_POST['reasoN'];
if(empty($reasoN))
{
$reasonErr="You didn't select any services.";
}
else
{
$N = count($reasoN);
$reasonErr="You selected $N services(s): ";
}
// if comment section is not empty then run test_input function to purge possible malicious code
if (empty($_POST["freecomments"]))
{$freecomments = "";}
else
{$freecomments = test_input($_POST["freecomments"]);}
}
$host="fdb3.biz.nf"; //localhost
$dbuser="1546259_rsginfo"; //user
$dbpass="RSGnow12"; //pass
$dbname="1546259_rsginfo"; //db name
// Create connection
$conn=mysqli_connect($host,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//create query
$sql= "INSERT INTO customer (fname, lname, email, phone, comments)VALUES ('$firstname', '$lastname', '$email', '$cellphone', '$freecomments')";
$sql2= "INSERT INTO DogInfo (DogName, Breed, Lookingfor)VALUES ('$dogname', '$Breed', '$reasoN')";
// execute query
mysqli_query($conn,$sql);
mysqli_query($conn, $sql2);
// close connection
mysqli_close($conn)
?>
<form id="form1" name="form1" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
<fieldset id="field1">
<legend id="legend1">Contact info:</legend>
<hr />
First name: <input type="text" id="firstname" name="firstname" size="30" class="textfield" value="<?php echo $firstname;?>">
<span class="error">* <?php echo $firstnameErr;?></span>
E-mail: <input type="text" size="30" name="email" class="textfield" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span><br />
Last name: <input type="text" id="lastname" name="lastname" size="30" class="textfield" value="<?php echo $lastname;?>">
<span class="error">* <?php echo $lastnameErr;?></span>
Cell: <input type="text" id="cellphone" name="cellphone" size="30" class="textfield" value="<?php echo $cellphone;?>">
<span class="error">* <?php echo $cellphoneErr;?></span><br />
</fieldset>
<fieldset id="field2">
<legend id="legend2">Doggie info:</legend>
<hr />
Name: <input type="text" id="dogname" name="dogname" size="20" class="textfield" value="<?php echo $dogname;?>"><span class="error">* <?php echo $dognameErr;?></span>
Breed: <input type="text" id="Breed" name="Breed" size="20" class="textfield" value="<?php echo $Breed;?>"><span class="error">* <?php echo $BreedErr;?></span>
<p>
Gender:<select name="genDer" class="textfield">
<option value="">--</option>
<option value="Intact Male" <?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Intact Male" ? "selected" : "" ?>>Intact Male</option>
<option value="Neutered Male"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Neutered Male" ? "selected" : "" ?>>Neutered Male</option>
<option value="Intact Female"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Intact Female" ? "selected" : "" ?>>Intact Female</option>
<option value="Neutered Female"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Neutered Female" ? "selected" : "" ?>>Neutered Female</option>
</select><span class="error">* <?php echo $genDerErr;?></span>
</p>
</fieldset>
<fieldset id="field3">
<legend id="legend3">Services Required:</legend>
<hr />
<input type="checkbox" name="reasoN[]" value="walkSale"
<?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking for a Dog Walker!
<input type="checkbox" name="reasoN[]" value="RawSale"
<?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking to purchase Raw Food!
<input type="checkbox" name="reasoN[]" value="groomSale"
<?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking for a Dog Groomer!
<span class="error">* <?php echo $reasonErr;?></span>
<?php echo $reasonConfirm;?>
</fieldset>
<fieldset id="field4">
<legend id="legend4">Comments & Questions</legend>
<hr />
<textarea rows="7" cols="90" id="freecomments" name="freecomments"><?php echo $freecomments;?></textarea>
</fieldset>
<input id="submit" type="submit" name="submit" value="submit">
</form>
</div>
<?php
echo "<h2>Your Input:</h2>";
echo $firstname;
echo "<br>";
echo $lastname;
echo "<br>";
echo $email;
echo "<br>";
echo $cellphone;
echo "<br>";
echo $dogname;
echo "<br>";
echo $Breed;
echo "<br>";
echo $genDer;
echo "<br>";
echo $reasoN;
echo "<br>";
echo $freecomments;
?>
</body>
</html>
Your code actually tries to insert values in to the table whether or not the validation is successful. The easiest and the quickest solution for this is to use a boolean flag.
eg:
// ...
$formValid = true; // Define a boolean and set to true before validating
//if conditional statement stops PHP from looking for variable values until the submit button is hit
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// check if a first name was provided
if (empty($_POST["firstname"]))
{
$firstnameErr = "A first name is required";
} else {
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
{
$firstnameErr = "Only letters and white space allowed";
$formValid = false; // Invalid input - set the flag to false
}
}
}
// ....
// Eventually wrap the mysql logic inside a condition
if ($formValid)
{
// Create connection
$conn=mysqli_connect($host,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//create query
$sql= "INSERT INTO customer (fname, lname, email, phone, comments)VALUES ('$firstname', '$lastname', '$email', '$cellphone', '$freecomments')";
$sql2= "INSERT INTO DogInfo (DogName, Breed, Lookingfor)VALUES ('$dogname', '$Breed', '$reasoN')";
// execute query
mysqli_query($conn,$sql);
mysqli_query($conn, $sql2);
// close connection
mysqli_close($conn);
}
// ... rest of your code