I'm using a form to insert records into my database. The error checking works and the records insert correctly. The problem is the record insert message displays above the form instead of underneath it. I've tried moving the INSERT query so it dislays under the form but when I do, the error checking doesn't work. Any help resolving this would be greatly appreciated.
<p class="first"><span class="error">* required field.</span></p>
<br>
<?php
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$servername = "localhost";
$username = "oldga740_Tonymm";
$password = "JtAjDm#6";
$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-z 0-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 = "Date received 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/NewProject.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>
</div>
</div>
</body>
</html>
Use a variable a store the message and then display it wherever you need, like this:
// your code
if(isset($_POST['submit']) && !$connection->connect_error){
// your code
if(!$error){
$query = "INSERT INTO Projects (Project, Client, LastName, DateReceived) VALUES ('$Project', '$Client', '$LastName', '$DateReceived')";
if($connection->query($query)){
$message = "record is successfully inserted!";
}else{
$message = "error: record could not be inserted";
}
}
}
?>
<?php
$connection->close();
?>
<form action="http://www.oldgamer60.com/Project/NewProject.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>
<?php
if(isset($message)){ echo $message; }
?>
// your code
Related
how to pass the collected input to another page after self validate in php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<body>
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr =$mobileTelNoErr = $sendMethodErr = "";
$forename = $surname = $email = $postalAddress = $landLineTelNo = $mobileTelNo = $sendMethod = "";
if($_SERVER["REQUEST_METHOD"] =="POST"){
$valid = true;
if(empty($_POST["forename"])){
$forenameErr = "Forename is required";
$valid = false; //false
} else {
$forename = test_input($_POST["forename"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["surname"])){
$surnameErr = "Surname is required";
$valid = false; //false
} else {
$surname = test_input($_POST["surname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["postalAddress"])){
$postalAddressErr =" Please enter postal address";
$valid = false; //false
} else {
$postalAddress = test_input($_POST["postalAddress"]);
}
if(empty($_POST["landLineTelNo"])){
$landLineTelNoErr = "Please enter a telephone number";
$valid = false; //false
} else {
$landLineTelNo = test_input($_POST["landLineTelNo"]);
// check if invalid telephone number added
if (!preg_match("/^[0-9 ]{7,}$/",$landLineTelNo)) {
$landLineTelNoErr = "Invalid telephone number entered";
}
}
if(empty($_POST["mobileTelNo"])){
$mobileTelNoErr = "Please enter a telephone number";
$valid = false; //false
} else {
$mobileTelNo = test_input($_POST["mobileTelNo"]);
// check if invalid telephone number added
if (!preg_match("/^[0-9 ]{7,}$/",$mobileTelNo)) {
$mobileTelNoErr = "Invalid telephone number entered";
}
}
if(empty($_POST["email"])){
$emailErr = "Email is required";
$valid = false; //false
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if(empty($_POST["sendMethod"])){
$sendMethodErr = "Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//if valid then redirect
if($valid){
header('Location: userdetail.php');
exit();
}
}
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<nav>
<ul>
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>WireFrame</li>
</ul>
</nav>
<form id = "userdetail" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="forename">Forename: </label>
<input type="text" name="forename" id="forename" value="<?php echo $forename;?>">
<span class="error">* <?php echo $forenameErr;?></span>
</p>
<p>
<label for="surname">Surname:</label>
<input type="text" name="surname" id="surname" value="<?php echo $surname;?>">
<span class="error">* <?php echo $surnameErr;?></span>
</p>
<p>
<label for="postalAddress">Postal Address:</label>
<input type="text" name="postalAddress" id="postalAddress" value="<?php echo $postalAddress;?>">
<span class="error"> </span>
</p>
<p>
<label for="landLineTelNo">Landline Telephone Number:</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" value="<?php echo $landLineTelNo;?>" >
<span class="error"> * <?php echo $landLineTelNoErr;?></span>
</p>
<p>
<label for="mobileTelNo">Moblie:</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" placeholder="example:012-3456789" value="<?php echo $mobileTelNo;?>" />
<span class="error"><?php echo $mobileTelNoErr;?></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" value="<?php echo $email;?>" placeholder="example:123#hotmail.com"/>
<span class="error"> </span>
</p>
<fieldset id="future">
<legend>Lastest news</legend>
<p>
Choose the method you recommanded to recevive the lastest information
</p>
<br>
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="SMS") echo "checked";?> value="SMS">
SMS
<span class="error">* <?php echo $sendMethodErr;?></span>
</fieldset>
<p><span class="error">* required field.</span></p>
<input type="checkbox" name="checkbox" value="check" id="agree" />
I have read and agree to the Terms and Conditions and Privacy Policy
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
</fieldset>
</form>
</div>
</body>
</html>
here is my php form...
it can validate itself in the same page but couldn't pass the data to another php page....
here is my another php code...
<?php
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr =$mobileTelNoErr = $sendMethodErr = "";
$forename = $surname = $email = $postalAddress = $landLineTelNo = $mobileTelNo = $sendMethod = "";
echo "<h1>Successfull submission :</h1>";
echo "<p>Forename : $forename <p/>";
echo "<p>Surname : $surname <p/>";
echo "<p>Email: $email</p>";
echo "<p>Post Address: $postalAddress</p>";
echo "<p>Landline: $landLineTelNo</p>";
echo "<p>Mobile : $mobileTelNo</p>";
echo "<p>Contact method: $sendMethod";
?>
You can use $_SESSION variables.
PHP $_SESSIONS
PHP Sessions and Cookies
So after the users has been validated set $_SESSION['surname'] = $surname;
Then on the top of each page add session_start(); to the top.
Then Under that add
if (isset($_SESSION['surname'])) {
$surname = $_SESSION['surname'];
} else {
die();
}
View the PHP docs for a more thorough understanding.
You may also want to look into setting up a MYSQL database if you want users to be able to create accounts.
Edit: form page
if($valid){
$_SESSION['surname'] = $surname;
$_SESSION['postalAddress'] = $postalAddress;
header('Location: userdetail.php');
exit();
}
My form 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'm working on an HTML form, which is connected to MySQL database. Database is updating with new data every time, when I reload the page and also when a failed submit occur.
This is my code, Anyone please help me to add session to this page and please give me a solution
<body>
<?php
// define variables and set to empty values
$email_id = $first_name = $last_name = $district = $city = $address = $mobile_no = $password = "";
$email_idErr = $first_nameErr = $last_nameErr = $districtErr = $cityErr = $addressErr = $mobile_noErr = $passwordErr = "";
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//First name validation
if(empty($_POST["first_name"]))
{$first_nameErr="First name is required";}
else
{$first_name = test_input($_POST["first_name"]);
//checking name formats
if(!preg_match("/^[a-zA-Z]*$/",$first_name))
{$first_nameErr="Only letters and white spaces allowed";}
}
//Second name validation
if(empty($_POST["last_name"]))
{$last_nameErr="Last name is required";}
else
{$last_name = test_input($_POST["last_name"]);
//checking name formats
if(!preg_match("/^[a-zA-Z]*$/",$last_name))
{$last_nameErr="Only letters and white spaces allowed";}
}
//E-mail validation
if(empty($_POST["email_id"]))
{$email_idErr="E-mail id is required";}
else
{$email_id = test_input($_POST["email_id"]);
//checking email format
if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email_id))
{$email_idErr="Invalid email format";}
}
//District is required
if(empty($_POST["district"]))
{ $districtErr="District is required";}
else
{ $district = test_input($_POST["district"]);
if(!preg_match("/^[a-zA-Z]*$/",$district))
{$districtErr="Only letters and white spaces allowed";}
}
$city = test_input($_POST["city"]);
$address = test_input($_POST["address"]);
//Mobile number validation
if(empty($_POST["mobile_no"]))
{$mobile_noErr="Mobile number is required";}
else
{$mobile_no = test_input($_POST["mobile_no"]);
if(!preg_match("/^[0-9]*$/",$mobile_no))
{$mobile_noErr="Invalid Mobile number";}
}
//Password validation
if(empty($_POST["password"]))
{$passwordErr="Password is required";}
else
{ $password = test_input($_POST["password"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
$con=mysqli_connect("localhost","root","","ashlyn");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{echo "Connection Established";}
$sql="INSERT INTO user_details (email_id, first_name, last_name, district, city, address, mobile_no, password)
VALUES ('$email_id', '$first_name', '$last_name', '$district', '$city', '$address', '$mobile_no', '$password')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "You are successfully registered..";
mysqli_close($con);
?>
<section class="container">
<div class="login">
<h1>User Login Page</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);>">
<p><input type="text" name="first_name" value="" placeholder="First Name"><span class="error">* <?php echo $first_nameErr;?></span></p>
<p><input type="text" name="last_name" value="" placeholder="Last Name"> <span class="error">* <?php echo $last_nameErr;?></span>
</p>
<p><input type="text" name="email_id" value="" placeholder="Email"><span class="error">* <?php echo $email_idErr;?></span>
</p>
<p><input type="text" name="district" value="" placeholder="District"><span class="error">* <?php echo $districtErr;?></span></p>
<p><input type="text" name="city" value="" placeholder="City">
</p>
<p><input type="text" name="address" value="" placeholder="Address">
</p>
<p><input type="text" name="mobile_no" value="" placeholder="Mobile Number"> <span class="error">* <?php echo $mobile_noErr;?></span>
</p>
<p><input type="password" name="password" value="" placeholder="Password"> <span class="error">* <?php echo $passwordErr;?></span>
</p>
<p class="submit"><input type="submit" name="submit" value="Submit"></p>
</form>
what you need is
<?php session_start();
on the first line bevor any output
https://stackoverflow.com/a/8084900/1792420
I'm doing the form validation using php.I'm trying to access the php file from my form(<form action="appoint.php">).But it shows me undefined variable error at each of the form elements.(code works well when i use the
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">which means i used form(html) and php in the same file.
here is my form code:
<form method="post" action="appoint.php">First Name:
<input type="text" name="fname" value="<?php echo $fname;?>"> <span class="error">* <?php if(isset($error['fname']))
echo $error['fname'];?></span>
<br>
<br>Last Name:
<input type="text" name="lname" value="<?php echo $lname;?>"> <span class="error">* <?php if(isset($error['lname']))
echo $error['lname'];?></span>
<br>
<br>E-mail:
<input type="text" name="email" value="<?php echo $email;?>"> <span class="error">* <?php if(isset($error['email']))
echo $error['email'];?></span>
<br>
<br>Phone-no:
<input type="text" name="phone_no" value="<?php echo $phone_no;?>"> <span class="error">* <?php if(isset($error['phone_no']))
echo $error['phone_no'];?></span>
<br>
<br>Date:
<input type="text" name="date" value="<?php echo $date;?>"> <span class="error">* <?php if(isset($error['date']))
echo $error['date'];?></span>
<br>
<br>Time:
<input type="text" name="time" value="<?php echo $time;?>"> <span class="error">* <?php if(isset($error['time']))
echo $error['time'];?></span>
<br>
<br>Physician:
<input type="text" name="physician" value="<?php echo $physician;?>"> <span class="error">* <?php if(isset($error['physician']))
echo $error['physician'];?></span>
<br>
<br>Remarks :
<input type="text" name="remarks" value="<?php echo $remarks;?>"> <span class="error">* <?php if(isset($error['remarks']))
echo $error['remarks'];?></span>
complaint:
<textarea name="complaint" rows="5" cols="40" value="<?php echo $complaint;?>"></textarea> <span class="error">* <?php if(isset($error['complaint']))
echo $error['complaint'];?></span>
<br>
<br>
<input type="submit" name="submit" value="Submit">
</form>
and here is my appoint.php
`
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["fname"]))
{$error['fname']= "First Name is required";}
else
{
$fname = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname))
{
$error['fname'] = "Only letters and white space allowed";
}
}
if (empty($_POST["lname"]))
{$error['lname']= "Last Name is required";}
else
{
$lname = test_input($_POST["lname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lname))
{
$error['lname'] = "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["phone_no"]))
{$phone_no = '00-0000-0000';}
else
{
$phone_no = test_input($_POST["phone_no"]);
// check if phone.no is valid//
if(!preg_match("/^[0-9]{2}-[0-9]{4}-[0-9]{4}$/", $phone_no))
{
$error['phone_no'] = "Invalid Number";
}
}
if (empty($_POST["date"]))
{$error['date'] = "Date is required";}
else
{$date= test_input($_POST["date"]);}
if (empty($_POST["time"]))
{$error['time'] = "Time is required";}
else
{$time = test_input($_POST["time"]);}
if(empty($_POST["physician"]))
{$error['physician']="select a physician";}
else {$physician=test_input($_POST["physician"]);
}
if (empty($_POST["remarks"]))
{$error['remarks'] ="";}
else
{
$remarks = test_input($_POST["remarks"]);}
if (empty($_POST["complaint"]))
{$error['complaint'] = " complaint is required";}
else
{
$complaint = test_input($_POST["complaint"]);}
if(empty($error))
{$con=mysqli_connect("localhost","root","root","my_db1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO np_appointment(fname,lname,date,time,email,phone_no,
physician,remarks,complaint)
VALUES
('$_POST[fname]','$_POST[lname]','$_POST[date]',
'$_POST[time]','$_POST[email]','$_POST[phone_no]',
'$_POST[physician]','$_POST[remarks]','$_POST[complaint]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con); }
}
?>
`
You can try a different approach:
Make all the fields required in html.
<input type="text" name="fname" value="<?php echo $fname;?>" required>
Then on the php do this. Define the variable outside the if-else sections.:
$fname = '';
if (empty($_POST["fname"]))
{$error['fname']= "First Name is required";}
else
{
$fname = test_input($_POST["fname"]);
}
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 } ?>