revalidate form and checking each input after editing - php

I created the fields that has validation process like required fields, numbers only and valid email.
it displays the errors simultaneously after submit but upon changing only one of the fields, it accepts and does not revalidate the other.
example
name = Error : required field
telephone = Error : numbers only
email = Error : not a valid email
after i corrected only the email , it accepts and proceed on submitting without rechecking the others.
please see my code . thanks in advance
<?php
include("conn/db.php");
function renderForm($name ='', $tel = '', $email ='', $error='', $error2='', $error3='')
{
?>
<html >
<head> <title>Form</title></head>
<body>
<?php
if ($error != '') {
echo $error
}
if ($error2 != '') {
echo $error2;
}
if ($error3 != '') {
echo $error3;
}
?>
<form action="" method="post">
Name : <input type = "text" class = "form-control" name = "name_text" value="<?php echo $name; ?>"> <br/>
Tel :<input type = "text" class = "form-control" name = "tel_text" value="<?php echo $tel; ?>"> <br/>
Email :<input type ="text" class = "form-control " name = "email_text" value="<?php echo $email; ?>" > <br/>
<input name= "submit" type="submit" value="Update" class = "btn btn-primary" >
</form>
</body>
</html>
<?php
}
if (isset($_POST['submit'])){
$name = $_POST['name_text'];
$tel = $_POST['tel_text'];
$email = $_POST['email_text'];
if ($name== '' ){
$error = 'ERR: required field';
}
if(!is_numeric($telephone)){
$error2 = 'ERR: numbers only';
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error3 = 'ERR: Email not valid';
}
else
{
***WILL PROCESS THE SQL QUERY ***
header("Location: main.php");
}
renderForm($name, $tel , $email ,$error, $error2, $error3);
}
else{
renderForm();
}
$con->close();
?>

<?php
include("conn/db.php");
function renderForm($name ='', $tel = '', $email ='', $error='', $error2='', $error3='')
{
?>
<html >
<head> <title>Form</title></head>
<body>
<?php
if ($error != '') {
echo $error
}
if ($error2 != '') {
echo $error2;
}
if ($error3 != '') {
echo $error3;
}
?>
<form action="" method="post">
Name : <input type = "text" class = "form-control" name = "name_text" value="<?php echo $name; ?>"> <br/>
Tel :<input type = "text" class = "form-control" name = "tel_text" value="<?php echo $tel; ?>"> <br/>
Email :<input type ="text" class = "form-control " name = "email_text" value="<?php echo $email; ?>" > <br/>
<input name= "submit" type="submit" value="Update" class = "btn btn-primary" >
</form>
</body>
</html>
<?php
}
if (isset($_POST['submit'])){
$name = $_POST['name_text'];
$tel = $_POST['tel_text'];
$email = $_POST['email_text'];
$is_valid = true;
if ($name== '' ){
$error = 'ERR: required field';
$is_valid = false;
}
if(!is_numeric($telephone)){
$error2 = 'ERR: numbers only';
$is_valid = false;
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error3 = 'ERR: Email not valid';
$is_valid = false;
}
if($is_valid) {
***WILL PROCESS THE SQL QUERY ***
header("Location: main.php");
}
renderForm($name, $tel , $email ,$error, $error2, $error3);
}
else{
renderForm();
}
$con->close();
?>
Its just a small mistake:
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error3 = 'ERR: Email not valid';
} else {
***WILL PROCESS THE SQL QUERY ***
header("Location: main.php");
}
You only checked the email and if it is corecct it was proceding. It did not include the other 2 checks for name and number.
I added a small variable to check if all 3 are correct.

Related

how to connect to sql after selfvalidate

my form action is php_self so that it can validate the form...
what i want to do is after the form is submited, then the data is connect and send to sql....
i already import my sql table and it have a few data recorded inside the table....
so how can i connect to the sql??
and also where i should write my connect sql code in???
here is my php form code....
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function disableSubmit() {
document.getElementById("submit").disabled = true;
}
function activateButton(element) {
if(element.checked) {
document.getElementById("submit").disabled = false;
}
else {
document.getElementById("submit").disabled = true;
}
}
</script>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
<body onload="disableSubmit()">
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr = $mobileTelNoErr = $sendMethodErr = $checkErr ="";
$valid = true;
// if forename is null , make it null , else test_input()
$forename = empty($_POST["forename"]) ? NULL : test_input($_POST["forename"]);
// if surname is null , make it null , else test_input()
$surname = empty($_POST["surname"]) ? NULL : test_input($_POST["surname"]);
// if postalAddress is null , make it null , else test_input()
$postalAddress = empty($_POST["postalAddress"]) ? NULL : test_input($_POST["postalAddress"]);
// if landLineTelNo is null , make it null , else test_input()
$landLineTelNo = empty($_POST["landLineTelNo"]) ? NULL : test_input($_POST["landLineTelNo"]);
// if mobileTelNo is null , make it null , else test_input()
$mobileTelNo = empty($_POST["mobileTelNo"]) ? NULL : test_input($_POST["mobileTelNo"]);
//email
$email = empty($_POST["email"]) ? NULL : test_input($_POST["email"]);
// if sendMethod is null , make it null , else test_input()
$sendMethod = empty($_POST["sendMethod"]) ? NULL : test_input($_POST["sendMethod"]);
if (isset($_POST["submit"])){
//check forename
if($forename === NULL) {
//forename is empty
$forenameErr = "*Forename is required";
$valid = false;
} else {
//check characters
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
$valid = false;
}
}
//check surname
if($surname === NULL){
//surname is empty
$surnameErr = "*Surname is required";
$valid = false; //false
} else {
//check charaters
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "*Only letters and white space allowed";
$valid = false;
}
}
//check address
if (!preg_match("/^[a-zA-Z0-9\-\\,. ]*$/", $postalAddress)) {
// check characters
$postalAddressErr = "*Invalid Postal Address";
$valid = false;//false
}
// check if invalid telephone number added
if (!preg_match("/^$|^[0-9]{12}$/",$landLineTelNo)) {
//check number
$landLineTelNoErr = "*Only 12 digit number can be entered";
$valid = false;//false
}
//check valid mobiel tel no
if (!preg_match("/^$|^[0-9]{11}$/",$mobileTelNo)) {
//check number
$mobileTelNoErr = "*Only 11 digit number can be entered";
$valid = false;//false
}
//check valid email
if (isset($email) && !filter_var($email, FILTER_VALIDATE_EMAIL))
{ $emailErr = "*Invalid email format";
$valid = false;//false
}
//check sendMethod
if($sendMethod === NULL){
//send method is empty
$sendMethodErr = "*Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//sendmethod link to information filled
if (isset($sendMethod) && $sendMethod=="email" && $email ==NULL){
$emailErr ="*Email is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="post" && $postalAddress ==NULL){
$postalAddressErr ="*Postal Address is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="SMS" && $mobileTelNo ==NULL){
$mobileTelNoErr ="*Mobile number is required ";
$valid = false;
}
if(empty($_POST['agree']) || $_POST['agree'] != 'agree') {
$checkErr ="Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy";
}
//if valid then redirect
if($valid){
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
$_SESSION['email'] = $email;
$_SESSION['postalAddress'] = $postalAddress;
$_SESSION['landLineTelNo'] = $landLineTelNo;
$_SESSION['mobileTelNo'] = $mobileTelNo;
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
}
} else{
//user did not submit form!
}
//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"> <?php echo $postalAddressErr;?></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" 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;?>">
<span class="error"> </span> <?php echo $emailErr;?> </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" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="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="terms" id="terms" onchange="activateButton(this)">
I Agree Terms & Coditions
<br><br>
<input type="submit" name="submit" id="submit">
</fieldset>
</form>
</div>
</body>
</html>
the userdetail.php is the page that shows the information that user submit...
so where and how i can insert the data in to sql....
You should write your SQL code within $valid.
Let me illustrate below:
Note: I've used default credentials: Hostname = localhost, username = root, password = '', database name = my_database.
You may refer to this: mysqli_connect()
if($valid){
echo "Valid data<br/>"; // Debugging code
echo '</pre>';
print_r($_POST);
exit;
/* SQL code starts */
$con = mysqli_connect("localhost", "root", "", "my_database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO...."; // Your insert query
$query = mysqli_query($con,$sql) or die(mysqli_error($con));
/* SQL code ends */
if ($query) { // Add this condition. Session should be written only when SQL query is successful
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
..........
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
} else {
echo "Unable to insert";
}
} else{
echo "Invalid data<br/>"; // Debugging code
echo '</pre>';
print_r($_POST);
exit;
}
Hope this helps.

Indicating Required Fields in PHP

I'm trying to create a PHP file of a process form that indicates the required fields when processed. The code that I have is:
<html>
<head>
<style type="text/css">
.error{color: #FF0000;}
</style>
</head>
<body>
<?php
if(isset($_POST['fullname']) && $_POST['fullname'] != "") {
$fullname = $_POST['fullname'];
}
if(isset($_POST['email']) && $_POST['email'] != "") {
$email = $_POST['email'];
}
if(isset($_POST['feedback']) && $_POST['feedback'] != "") {
$text= $_POST['feedback'];
}
$nameErr = $emailErr = "";
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == POST) {
if (empty($_POST["fullname"])){
$nameErr = "Name is required";
} else {
$name = test_input($_POST["fullname"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
}
?>
<h1>Customer Feedback</h1>
<p1>Please tell us what you think</p1><br><br>
<form method='POST' action='<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>' >
<p1>Your name:</p1><br>
<input type="text" name="fullname" value="<?php echo $fullname; ?>"><br><br>
<p1>Your email address:</p1><br>
<input type="text" name="email" value="<?php echo $email; ?>"><br><br>
<p1>Your feedback:</p1><br>
<textarea rows="5" cols="50" name="feedback"><?php echo $text;?></textarea><br><br>
<input type="submit" Value="Send Feedback"><br><br>
<?php
error_reporting(E_ALL);
$name = $_POST['fullname'];
$email = $_POST['email'];
$feed = $_POST['feedback'];
if (empty($name))
{
echo "Please enter your name, email and feedback.";
}
if (empty($email))
{
echo "Please enter your email and feedback.";
}
if (empty($feed))
{
echo "Please enter feedback.";
}
if (!empty($name) && !empty($email) && !empty($feed))
{
echo "You have inserted the correct data";
}
?>
</form>
</body>
</html>
However, when I run it on Chrome, I got a server error 500 saying that
The website encountered and error while retrieving process_4.php. It maybe down for maintenance or configured incorrectly.
The other PHP files that I've made leading up to this point have all worked correctly and I don't know why this one isn't.

PHP Variable not storing value after submit

I have a simple PHP page, and am attempting to validate form input.
Upon hitting submit with invalid data, the inputted value is not being returned in my echo statement
I want to echo the input as the value so that the user can understand what they typed wrong. Below is my code;
Neither the echo of "TEST" . $contactEmail nor the input value are displaying $contactEmail
<?php
// define variables and set to empty values
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = test_input($_POST["contactFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = test_input($_POST["contactEmail"]);
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = test_input($_POST["retailerID"]);
}
}
?>
<!--Begin HTML Form-->
<div class="Form_container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Contact First Name<span class="required">*</span><span class="formError"><?php echo $contactFirstNameErr;?></span><br> <!--<p class='spacerLine'></p>-->
<input type="text" class="largeInput" name="contactFirstName" value="<?php echo $contactFirstName;?>">
<br><br>
Contact E-mail<span class="required">*</span><span class="formError"> <?php echo $contactEmailErr;?></span><br>
<input type="text" class="largeInput" name="contactEmail" value="<?php echo $contactEmail;?>">
<br><br>
<?php echo "TEST" . $contactEmail;?>
<br><br>
Retailer<span class="required">*</span><span class="formError"><?php echo $retailerIDErr;?></span><br>
<input type="text" class="largeInput" name="retailerID" value="<?php echo $retailerID;?>">
<br><br>
<input type="submit" class="button" name="submit" value="Add Contact">
</form>
</div>
Any thoughts? I'm new to PHP but have been following the W3 tutorial pretty tightly. Could it be my classes throwing things off? Or did I just mess up a variable name?
Thanks for all help
I want to echo the input as the value so that the user can understand what they typed wrong.
Neither the echo of "TEST" . $contactEmail nor the input value are displaying $contactEmail
First of all, echo $_POST values instead of $contactFirstName, $contactEmail etc. because these values are available only after it crosses all the validation steps.
Second, there's no function named test_input() in your code, or may be it is defined somewhere else.
And finally, look at this statement here:
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { ..
There's no variable named $email in your code. It should be:
if (!filter_var($_POST["contactEmail"], FILTER_VALIDATE_EMAIL)) { ..
So your code should be like this:
<?php
function test_input($string){
// your code
}
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = test_input($_POST["contactFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (!filter_var($_POST["contactEmail"], FILTER_VALIDATE_EMAIL)) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = test_input($_POST["contactEmail"]);
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = test_input($_POST["retailerID"]);
}
}
?>
<div class="Form_container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Contact First Name<span class="required">*</span><span class="formError"><?php echo $contactFirstNameErr; ?></span><br>
<input type="text" class="largeInput" name="contactFirstName" value="<?php if(isset($_POST['contactFirstName'])){ echo $_POST['contactFirstName']; } ?>">
<br><br>
Contact E-mail<span class="required">*</span><span class="formError"> <?php echo $contactEmailErr;?></span><br>
<input type="text" class="largeInput" name="contactEmail" value="<?php if(isset($_POST['contactEmail'])){ echo $_POST['contactEmail']; } ?>">
<br><br>
<?php
echo "TEST ";
if(isset($_POST['contactEmail'])){ echo $_POST['contactEmail']; }
?>
<br><br>
Retailer<span class="required">*</span><span class="formError"><?php echo $retailerIDErr;?></span><br>
<input type="text" class="largeInput" name="retailerID" value="<?php if(isset($_POST['retailerID'])){ echo $_POST['retailerID']; } ?>">
<br><br>
<input type="submit" class="button" name="submit" value="Add Contact">
</form>
</div>
Here's the reference for isset() function:
isset()
Sidenote: Even though this answer will work you temporarily, but you should definitely look at how to strictly validate form inputs using regex.
The below line validates the value of the variable $email, but i can't see anywhere in your code where does that variable get set a value, that can be the first step in fixing the issue.
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
You are not defining test_input() function and $email is not defined in this line:
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
This code works for me so far:
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = $_POST["contactFirstName"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = $_POST["contactEmail"];
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = $_POST["retailerID"];
}
}

Trouble with my PHP validation script

So I have created a PHP validation script. On test I filled and submitted the forms but so far $error returns undefined index and no data is set into the database. Can anyone take a look and give a second opinion on why its not functioning as intended? To my eye it all looks OK.
Otherwise my script runs OK (Insert into DB) it's just something about my validation script breaks it.
<?php
if (isset($_POST['Submit'])) {
if ($_POST['name'] != "") {
$_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if ($_POST['name'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors .= 'Please enter a name.<br/>';
}
if (isset($_POST['Submit'])) {
if ($_POST['address'] != "") {
$_POST['address'] = filter_var($_POST['address'], FILTER_SANITIZE_STRING);
if ($_POST['address'] == "") {
$errors .= 'Please enter a valid address<br/><br/>';
}
} else {
$errors .= 'Please enter a address.<br/>';
}
if (isset($_POST['postcode'])) {
if ($_POST['postcode'] != "") {
$_POST['postcode'] = filter_var($_POST['postcode'], FILTER_SANITIZE_STRING);
if ($_POST['postcode'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors .= 'Please enter a name.<br/>';
}
if (!$errors) {
$name = $_POST['name'];
$address = $_POST['address'];
$postcode = $_POST['postcode'];
$photo = $_POST['photo'];
$db1 = new dbmember();
$db1->openDB();
$numofrows = $db1->insert_member('', $name, $address, $postcode, $photo);
echo "Success. Number of rows affected:
<strong>{$numofrows}<strong>";
$sql="SELECT * from member";
$result=$db1->getResult($sql);
echo "<table class='table table-hover'>";
echo "<tr><th>Member ID</th><th>Name</th><th>Address</th><th>Postcode</th><th>Photo</th></tr>";
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>{$row['mid']}</td><td>{$row['name']}</td>";
echo "<td>{$row['address']}";
echo "<td>{$row['postcode']}";
echo"<td><img height='80' width='120' src='{$row['photo'] }' /></td>";
echo "</tr>";
}
echo "</table>";
$db1->closeDB();
}
}
}
}
echo "Records updated!<br/><br/>";
} else {
echo '<div style="color: red">' . $errors . '<br/></div>';
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" name="myform" class = "well" id="myform" onsubmit="return validateForm( );">
Please fill in the fields to add a new member
<p></p>
<input type="text" class="span3" placeholder="Enter member name"name="name" id="name" /><br />
<input type="text" class="span3"placeholder="Enter an address"name="address" id="address" /><br />
<input type="text" class="span3"placeholder="Enter a postcode"name="postcode" id="postcode" /><br />
<input type="text"class="span3" placeholder="Enter a picture (optional)"name="photo" /><br />
<p>
<button class="btn btn-primary" type="submit" value="Save" >Submit </button>
</p>
</form>
Your button doesn't have a name="Submit" attribute. Your php code can't find the $_POST['Submit'] because it doesn't exist.
Consequently, the if (isset($_POST['Submit'])) { condition will return false meaning the validation is never performed and the $error variable never set to a value.

how to auto assign the word "NULL" in sql if the user do not fill in

after i submit the form, the data in the form is sent to sql...
the unfill text field sending nothing to the table....
how to auto assign the word "NULL" in sql if the user do not fill in anyhting in the form....
here is my php form code
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function disableSubmit() {
document.getElementById("submit").disabled = true;
}
function activateButton(element) {
if(element.checked) {
document.getElementById("submit").disabled = false;
}
else {
document.getElementById("submit").disabled = true;
}
}
</script>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
<body onload="disableSubmit()">
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr = $mobileTelNoErr = $sendMethodErr = $checkErr ="";
$valid = true;
// if forename is null , make it null , else test_input()
$forename = empty($_POST["forename"]) ? NULL : test_input($_POST["forename"]);
// if surname is null , make it null , else test_input()
$surname = empty($_POST["surname"]) ? NULL : test_input($_POST["surname"]);
// if postalAddress is null , make it null , else test_input()
$postalAddress = empty($_POST["postalAddress"]) ? NULL : test_input($_POST["postalAddress"]);
// if landLineTelNo is null , make it null , else test_input()
$landLineTelNo = empty($_POST["landLineTelNo"]) ? NULL : test_input($_POST["landLineTelNo"]);
// if mobileTelNo is null , make it null , else test_input()
$mobileTelNo = empty($_POST["mobileTelNo"]) ? NULL : test_input($_POST["mobileTelNo"]);
//email
$email = empty($_POST["email"]) ? NULL : test_input($_POST["email"]);
// if sendMethod is null , make it null , else test_input()
$sendMethod = empty($_POST["sendMethod"]) ? NULL : test_input($_POST["sendMethod"]);
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST["submit"])){
//check forename
if($forename === NULL) {
//forename is empty
$forenameErr = "*Forename is required";
$valid = false;
} else {
//check characters
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
$valid = false;
}
}
//check surname
if($surname === NULL){
//surname is empty
$surnameErr = "*Surname is required";
$valid = false; //false
} else {
//check charaters
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "*Only letters and white space allowed";
$valid = false;
}
}
//check address
if (!preg_match("/^[a-zA-Z0-9\-\\,. ]*$/", $postalAddress)) {
// check characters
$postalAddressErr = "*Invalid Postal Address";
$valid = false;//false
}
// check if invalid telephone number added
if (!preg_match("/^$|^[0-9]{12}$/",$landLineTelNo)) {
//check number
$landLineTelNoErr = "*Only 12 digit number can be entered";
$valid = false;//false
}
//check valid mobiel tel no
if (!preg_match("/^$|^[0-9]{11}$/",$mobileTelNo)) {
//check number
$mobileTelNoErr = "*Only 11 digit number can be entered";
$valid = false;//false
}
//check valid email
if (isset($email) && !filter_var($email, FILTER_VALIDATE_EMAIL))
{ $emailErr = "*Invalid email format";
$valid = false;//false
}
//check sendMethod
if($sendMethod === NULL){
//send method is empty
$sendMethodErr = "*Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//sendmethod link to information filled
if (isset($sendMethod) && $sendMethod=="email" && $email ==NULL){
$emailErr ="*Email is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="post" && $postalAddress ==NULL){
$postalAddressErr ="*Postal Address is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="SMS" && $mobileTelNo ==NULL){
$mobileTelNoErr ="*Mobile number is required ";
$valid = false;
}
if(empty($_POST['agree']) || $_POST['agree'] != 'agree') {
$checkErr ="Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy";
}
//connect to sql
if($valid){
/* SQL code starts */
$con = mysqli_connect("localhost", "root", "", "chollerton");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = $sql = "INSERT INTO ct_expressedinterest (forename, surname, email, postalAddress, landLineTelNo, mobileTelNo ,sendMethod) VALUES ('$forename', '$surname', '$email', '$postalAddress', '$landLineTelNo', '$mobileTelNo' ,'$sendMethod')";
$query = mysqli_query($con,$sql) or die(mysqli_error($con));
//if valid then redirect
if($valid){
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
$_SESSION['email'] = $email;
$_SESSION['postalAddress'] = $postalAddress;
$_SESSION['landLineTelNo'] = $landLineTelNo;
$_SESSION['mobileTelNo'] = $mobileTelNo;
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
}else {echo "Unable to insert";
}
} else{
//user did not submit form!
}
}
?>
<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"> <?php echo $postalAddressErr;?></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" 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;?>">
<span class="error"> </span> <?php echo $emailErr;?> </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" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="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="terms" id="terms" onchange="activateButton(this)">
I Agree Terms & Coditions
<br><br>
<input type="submit" name="submit" id="submit">
</fieldset>
</form>
</div>
</body>
</html>
In your database, what's the default value of the particular field?
It should be set to NULL as default. In that case, if you're not inserting any data for that particular field, it will insert NULL.

Categories