I decided to do a little test by testing to see if the form would detect an empty input field, and it didn't work, I don't know what the problem is and I don't want to write the rest of the project if this one small thing doesn't work so here's the code, I've looked over it and I don't think I've missed anything.
Here's the HTML:
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<form method="POST" action="myform.php">
<fieldset>
<legend>Personal Info</legend>
First name <input name="name" type="text">
Middle name <input name="middlename" type="text">
Surname <input name="lastname" type="text">
Age <input name="age" type="number">
Date of birth <input name="dob" type="date">
</fieldset>
<fieldset>
<legend>Regional & location info</legend>
Continent
<select>
<option value="europe">Europe</option>
<option value="americas">America</option>
<option value="africa">Africa</option>
<option value="asia">Asia</option>
<option value="australia">Australia</option>
<option value="eurasia">Eurasia</option>
</select>
Country <input type="text"> State <input type="text">
City <input type="text">
Street number <input type="number">
Street name <input type="text"> <br><br>
Suburb <input type="text"> Postcode <input type="number">
If none of these apply to your accommodations, enter a typed location here <input type="text">
</fieldset>
<fieldset>
<legend>Previous lifestyle accommodations</legend>
Previous &/or most recent job title <input name="job" type="text">
First time job seeker <input type="checkbox" name="check1" value="ftjb">
I'm a student <input type="checkbox" name="check2" value="ias">
Previous &/or most recent acedemic title <input name="school" type="text">
First time applying for a qualification <input type="checkbox" name="check3" value="ftafaq">
I have work experience <input type="checkbox" name="check4" value="ihwe">
</fieldset>
<fieldset>
<legend>Details of arrival</legend>
Reason for arrival of all parties <input name="reason" type="text">
Date of arrival <input name="arrival" type="date">
Amount of stay expectancy
<input type="checkbox" name="check3">Temporary
<input type="checkbox" name="check4">Longterm
</fieldset>
<fieldset>
<legend>Signiture</legend>
<input type="text">
</fieldset>
<input type="submit" value="Submit"><button type="reset">Reset</button>
</form>
</body>
</html>
And here's what I've done in PHP so far for the form:
<?php
$nameInvalid = "";
$middleInvalid = "";
$surnameInvalid = "";
$ageInvalid = "";
$dobInvalid = "";
$countryInvalid = "";
$cityInvalid = "";
$strtInvalid = "";
$strnameInvalid = "";
$suburbInvalid = "";
$postcodeInvalid = "";
$jobInvalid = "";
$ftjsInvalid = "";
$iasInvalid = "";
$schoolInvalid = "";
$check1Invalid = "";
$check2Invalid = "";
$checl3Invalid = "";
$check4Invalid = "";
$reasonInvalid = "";
$arrivalInvalid = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameInvalid = "Name is required";
}
}
?>
Please add name="submit" attribute into the button.
<input type="submit" value="Submit" name="submit">
And also please add echo into the validation to print validation message like below.
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
echo $nameInvalid = "Name is required";
}
}
Use this
<input type="submit" name="submit" value="Submit">
HTML
You need to use HTML5 validation to prevent the form from being sent if it doesn't conform to your rules.
From the official documentation:
The simplest HTML5 validation feature to use is the required attribute — if you want to make an input mandatory, you can mark the element using this attribute. When this attribute is set, the form won't submit (and will display an error message) when the input is empty (the input will also be considered invalid).
In your case, try adding the required tag to the fields you want to test, for instance the name field:
First name <input name="name" type="text" required>
To make it a little bit more fancy, add some CSS:
input:invalid {
border: 2px dashed red;
}
input:valid {
border: 2px solid black;
}
PHP
To validate PHP responses, all you need to do is the following:
if (!$_REQUEST["name"]) {
//If the name field is empty
die("Name is missing");
//Replace this with whatever logic fits your code
}
We're using $_REQUEST, which means both $_POST and $_GET, but you can stick to $_POST if you'd like. We're using if(!$val) to validate, it's the easiest way, but has caveats (see below), you can also use if(empty($val)) but for strings, the first is fine.
Get rid of the list of variables you define as empty in the beginning of your script. Instead look at setting an array if a value that shouldn't be empty, is empty. For instance:
# Repeat this structure for each form field you want
if (!$_REQUEST["name"]) {
//If the name field is empty
$empty_fields[] = "name";
//Fill the $empty_fields array with all the fields that are missing
}
# At the end, cycle thru the missing fields and tell the user
if(!empty($empty_fields)){
die("The following fields are missing: ".implode(", ", $empty_fields));
}
Caveat
Using a if(!$val) is a shortcut, and won't work if you allow values like " " (space) or "0" (zero), but works fine if you're expecting string values.
I checked code and its working properly. Just give name to submit button and echo validation message in php page.
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<form method="POST" action="test1.php">
<fieldset>
<legend>Personal Info</legend>
First name <input name="name" type="text">
Middle name <input name="middlename" type="text"> Surname <input name="lastname" type="text"> Age <input name="age" type="number"> Date of birth <input name="dob" type="date">
</fieldset>
<fieldset>
<legend>Regional & location info</legend>
Continent
<select>
<option value="europe">Europe</option>
<option value="americas">America</option>
<option value="africa">Africa</option>
<option value="asia">Asia</option>
<option value="australia">Australia</option>
<option value="eurasia">Eurasia</option>
</select>
Country <input type="text"> State <input type="text"> City <input type="text">
Street number <input type="number"> Street name <input type="text"> <br><br>
Suburb <input type="text"> Postcode <input type="number"> If none of these apply to your accommodations, enter a typed location here <input type="text">
</fieldset>
<fieldset>
<legend>Previous lifestyle accommodations</legend>
Previous &/or most recent job title <input name="job" type="text"> First time job seeker <input type="checkbox" name="check1" value="ftjb"> I'm a student <input type="checkbox" name="check2" value="ias"> Previous &/or most recent acedemic title <input name="school" type="text"> First time applying for a qualification <input type="checkbox" name="check3" value="ftafaq"> I have work experience <input type="checkbox" name="check4" value="ihwe">
</fieldset>
<fieldset>
<legend>Details of arrival</legend>
Reason for arrival of all parties <input name="reason" type="text"> Date of arrival <input name="arrival" type="date"> Amount of stay expectancy <input type="checkbox" name="check3">Temporary <input type="checkbox" name="check4">Longterm
</fieldset>
<fieldset>
<legend>Signiture</legend>
<input type="text">
</fieldset>
<input type="submit" name="submit" value="Submit">
<button type="reset">Reset</button>
</form>
</body>
</html>
Display echo message in php page.
<?php
$nameInvalid = "";
$middleInvalid = "";
$surnameInvalid = "";
$ageInvalid = "";
$dobInvalid = "";
$countryInvalid = "";
$cityInvalid = "";
$strtInvalid = "";
$strnameInvalid = "";
$suburbInvalid = "";
$postcodeInvalid = "";
$jobInvalid = "";
$ftjsInvalid = "";
$iasInvalid = "";
$schoolInvalid = "";
$check1Invalid = "";
$check2Invalid = "";
$checl3Invalid = "";
$check4Invalid = "";
$reasonInvalid = "";
$arrivalInvalid = "";
if (isset($_POST['submit']))
{
if (empty($_POST["name"]))
{
echo $nameInvalid = "Name is required";
}
}
?>
Its done.
Related
I'm learning some more PHP and after PHP itself to work, I can't seem to get it to validate any form field correctly. My goal is to check if the firstname field is empty, and if it is, it will give a message in a red color. The message in the red works, but only because the echo script is being called by the form submission, not because it has detected any empty field, because when I made an else statement to say "wassup" if its not empty, I got the same message for when the field is empty. Also, is there a way to check off multiple input fields at once like you could with JavaScript? For example if input1 == '' || input2 == '' and so on. Here is my HTML:
<html>
<head>
<title>Welcome</title>
</head>
<body>
<form action="welcome.php" method="post">
<fieldset>
<legend>Personal Info</legend>
First name <input name="name" type="text">
Middle name <input name="middlename" type="text">
Surname <input name="lastname" type="text">
Age <input name="age" type="number">
Date of birth <input name="dob" type="date">
</fieldset>
<fieldset>
<legend>Regional & location info</legend>
Continent
<select>
<option value="europe">Europe</option>
<option value="americas">America</option>
<option value="africa">Africa</option>
<option value="asia">Asia</option>
<option value="australia">Australia</option>
<option value="eurasia">Eurasia</option>
</select>
Country <input name="country" type="text"> State <input type="text">
City <input name="city" type="text">
Street number <input name="streetno" type="number">
Street name <input name="streetname" type="text"> <br><br>
Suburb <input name="suburb" type="text"> Postcode <input name="postcode" type="number">
If none of these apply to your accommodations, enter a typed location here <input type="text">
</fieldset>
<fieldset>
<legend>Previous lifestyle accommodations</legend>
Previous &/or most recent job title <input name="job" type="text">
First time job seeker <input type="checkbox" name="check1" value="ftjb">
I'm a student <input type="checkbox" name="check2" value="ias">
Previous &/or most recent acedemic title <input name="school" type="text">
First time applying for a qualification <input type="checkbox" name="check3" value="ftafaq">
I have work experience <input type="checkbox" name="check4" value="ihwe">
</fieldset>
<fieldset>
<legend>Details of arrival</legend>
Reason for arrival <input name="reason" type="text">
Date of arrival <input name="arrival" type="date">
Amount of stay expectancy
<input type="checkbox" name="check3">Temporary
<input type="checkbox" name="check4">Longterm
</fieldset>
<fieldset>
<legend>Signiture</legend>
<input name='signiture' type="text">
</fieldset>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Here is my PHP code:
<?php
$firstname = $_POST['name'];
$lastname = $_POST['lastname'];
$age = $_POST['age'];
$dob = $_POST['dob'];
$country = $_POST['country'];
$city = $_POST['city'];
$suburb = $_POST['suburb'];
$postcode = $_POST['postcode'];
$streetno = $_POST['streetno'];
$streetname = $_POST['streetname'];
$suburb = $_POST['suburb'];
$job = $_POST['job'];
$school = $_POST['school'];
$reason = $_POST['reason'];
$arrival = $_POST['arrival'];
$signiture = $_POST['signiture'];
if (isset($_POST['submit'])) {
if (empty($_POST[$firstname])) {
echo '<p style="color: red; text-align: center">Your first name is required</p>';
} else {
echo "wassaup";
}
}
?>
In your if statement, you need to do this:
if (empty($_POST['name'])) { //Or replace $_POST['name'] with $firstname
echo '<p style="color: red; text-align: center">Your first name is required</p>';
} else {
echo "wassaup";
}
You have a wrong syntax if (empty($_POST[$firstname])). You should use ' ' single paranthesis in firstname and remove this sign $.
change this if (empty($_POST[$name])) { to if (empty($_POST['firstname'])) { and check again. your syntax is wrong that's why it is not working.
Change in your code
if (!isset($_POST['firstname'] || empty($_POST['firstname'])) {
echo '<p style="color: red; text-align: center">Your first name is required</p>';
} else {
echo "wassaup";
}
First you can create error array where you will put all yours errors
$error = array();
then when you check for multiple fields
if (empty($_POST['firstname'])) $error[] = "First name can't be empty";
if (empty($_POST['lastname'])) $error[] = "Last name can't be empty";
// and so on
after you do all of this make statement to check if error array is empty, if not display errors
if (empty($error)) {
// do something
} else {
// error exists you want to display all errors
foreach ($error as $value) {
echo '<ul><li>'.$value.'</li></ul>';
}
}
in the html form, you have to add the attribute required in html tag and without using the PHP processing
First name <input name="name" type="text" required="required">
and if the user doesn't enter his First name, he will get the error message (that the first name is required)
This is a form that I get the user to enter data including their mobile number and mobile carrier. I am using concatenation of the mobile number and carrier to send a message to their phone. This works but I am having a problem with the concatenation for the email recipient. If I use a straight email address ("myemail#gmail.com"), it will deliver the content. It will not work using the concatenation of $phone and $carrier ($YourEmailAddress). I have tried several different methods but nothing is working. I have tried using "&" and "+". I need assistance in figuring out why the concatenation of the phone and carrier strings is not working. I am new to this site so I am not sure if I correctly posted this.
This is my php file:
<?php
if( count($_POST) )
{
$YourEmailSubject = "Form Submission From the Blog";
$name = stripslashes($_POST['name']);
$email = stripslashes($_POST['email']);
$comment = stripslashes($_POST['comment']);
$phone = ($_POST['phone']);
$selectOption = $_POST['carrier'];
$content = "$name\r\n$email\r\n$comment\r\n$selectOption\r\n";
$YourEmailAddress = $phone."#".$selectOption;
mail($YourEmailAddress,$YourEmailSubject,$content,"From: ABC Company");
header("Location:" . (isset($_POST['redirect']) ? $_POST['redirect'] : '/') );
exit;
}
?>
This is my form:
<form method="post" action="/simplecontact.php">
<input type="hidden" name="redirect" value="//www.google.com">
<p>
Name:<br>
<input type="text" name="name" style="width:200px;"></td>
</p>
<p>
Email:<br>
<input type="text" name="email" style="width:200px;"></td>
</p>
<p>
Comment:<br>
<textarea name="comment" style="width:200px; height:100px"></textarea></td>
</p>
<p>Phone Number:<br>
<input type="text" id="number" name="number" /></td>
</p>
Carrier: <br>
<select id="carrier" name="carrier">
<option value="tmomail.net">T-mobile</option>
<option value="vmobl.com">Virgin Mobile</option>
<option value="cingularme.com">Cingular</option>
<option value="messaging.sprintpcs.com">Sprint</option>
<option value="txt.att.net">AT&T</option>
<option value="vtext.com">Verizon</option>
<option value="messaging.nextel.com">Nextel</option>
<option value="email.uscc.net">US Cellular</option>
<option value="sms.mycricket.com">Cricket</option>
<option value="mymetropcs.com">Metro PCS</option>
<option value="myboostmobile.com">Boost Mobile</option>
</select>
<p>
<input type="submit" style="width:200px;" value="Submit Form"></td>
</p>
</form>
In your form the phone input name is "number", in the php code you are trying to get the phone number like the input name was "phone"
Just change the input name to "phone"
<input type="text" id="number" name="phone" /></td>
I have a HTML form with radio buttons, option boxes (drop down boxes), checkboxes, text fields and so on. I have the form pointed to another file called send.php to email the form on but how would I do this with the tickboxes and radio buttons and input text in between each answer? I would kind of like to format it like this:
Welcome: {name}
Your age group it between: {radio button with age groups}
And so on. I can't give you the actual code as it is private but I can give this instead which uses the kind of code and format:
<form action="send.php">
<input type="radio" name="AgeGroup" value="AgeGroup1"> 0-18<br>
<input type="radio" name="AgeGroup" value="AgeGroup2"> 19-29<br>
<input type="radio" name="period" value="AgeGroup3"> 30-39<br>
<input type="radio" name="period" value="AgeGroup4"> 40-49<br>
<input type="radio" name="period" value="AgeGroup5"> 50+<br>
<br><br><br><br>
<select name="Country">
<option value ="UK">United Kingdom</option>
<option value ="USA">United States</option>
</option></select>
<br><br><br><br>
<input type="text" name="PostCode" size="5">
<br><br><br><br>
<input type="text" name="HouseNumber" size="5">
<br><br><br><br>
<textarea id="Family" class="input" name="FamilyNumber" rows="10" cols="60"></textarea>
<br><br><br><br>
<input type="checkbox" name="Delievery" value="NextDay"> Next Day Delievery
<br>
<input type="checkbox" name="Delievery" value="TwoToFive"> 2-5 Day
<br>
<input type="checkbox" name="Outcome" value="Dismissed"> Dismissed
<br><br><br><br><br><br>
<center><button id="Send" type="submit" style="height:25px; width:100px; background-color: grey">Send</button></center>
</form>
Sorry it's so random. I ran out of ideas! Also sorry for my coding abilities, I don't normally do HTML!
Thanks.
I'm hoping this will help...if I'm understanding your question correctly.
Make sure to add a method to your form tag. For example:
<form action="send.php" method="post">. In send.php, you want to grab your variables by name attribute, for example:
$name = $_POST['Name'];
$ageGroup = $_POST['AgeGroup'];
And then you want to build out your email. PHP allows variables to be parsed in double quote strings, which can help you build your message the way you want it. (Reference)
$to = "person#example.com";
$subject = "Subject goes here";
$message = "Welcome: $name. Your age group is between: $ageGroup";
//note: headers are optional
$headers = "From: you#example.com" . "\r\n" . "CC: anotherperson#example.com";
mail($to, $subject, $message, $headers);
This is just a simple example, but this might be able to get you started.
you need to add method="POST" attribute to tag.
then, in send.php to read values, for example PostCode or HouseNumber:
echo "Post code: ".$_POST["PostCode"]."<br />";
echo "House number: "$_POST["HouseNumber"]";
for age:
if(isset($_POST["AgeGroup"]) {
echo "Age group: ".$_POST["AgeGroup"];
}
if(isset($_POST["period"]) {
echo "Age group: ".$_POST["period"];
}
for more info go to manual: http://php.net/manual/en/reserved.variables.post.php
This way you can group the radio buttons into one name, and you can get the values in the php as $_POST['name']
<form action="send.php" method="post">
<input type="radio" name="AgeGroup" value="0-18"> 0-18<br>
<input type="radio" name="AgeGroup" value="19-29"> 19-29<br>
<input type="radio" name="AgeGroup" value="30-39"> 30-39<br>
<input type="radio" name="AgeGroup" value="40-49"> 40-49<br>
<input type="radio" name="AgeGroup" value="50+"> 50+<br>
<select name="Country">
<option value ="UK">United Kingdom</option>
<option value ="USA">United States</option>
</option></select>
<input type="text" name="PostCode" size="5">
<input type="text" name="HouseNumber" size="5">
<textarea id="Family" class="input" name="FamilyNumber" rows="10" cols="60"></textarea>
<input type="checkbox" name="Delievery" value="NextDay"> Next Day Delievery
<br>
<input type="checkbox" name="Delievery" value="TwoToFive"> 2-5 Day
<br>
<input type="checkbox" name="Outcome" value="Dismissed"> Dismissed
<center><button id="Send" type="submit" style="height:25px; width:100px; background-color: grey">Send</button></center>
</form>
I have a html form where i want 3 fields to be mandatory. If the user doesn't fill any one of those fields, then the form shouldn't be submitted and it should tell the user to fill in the mandatory one's. I've used PDO and i dont know how to do it. If someone could help me. Down below i've given both my html and php files.
HTML:
<html>
<head>
<title>Data Insertion</title>
</head>
<body>
<p><span class="Error">* required field.</span></p>
<form method="post" action="su.php">
<h2>Please Fill In Details</h2>
<label for="name">Name </label>
<input type="text" Placeholder="Enter your name" name="name" id="name" />
<span class="Error">*</span>
<br />
<br />
<label for="age">Age </label>
<input type="text" name="age" id="age" placeholder="Enter your age" />
<br />
<br />
<label for="mailid">MailId </label>
<input type="text" name="mailid" id="mailid" placeholder="Enter your Mail Id" />
<span class="Error">*</span>
<br />
<br />
<label for="gender">Gender </label>
<br />
<label for="male">Male </label>
<input type="radio" name="gender" id="gender" value="Male" id="male" />
<label for="female">Female </label>
<input type="radio" name="gender" id="gender" value="Female" id="female" />
<br />
<br />
<label for="qualification">Qualification </label>
<select name="qualification" value="Qualification" id="qualification">
<option value="B.E">SSLC</option>
<option value="P.G">HSC</option>
<option value="SSLC">UG</option>
<option value="HSC">PG</option>
</select>
<br /><br />
<label for="hobbies">Hobbies </label>
<br />
<input type="checkbox" name="hobbies" id="hobbies" value="Cricket" />Cricket
<input type="checkbox" name="hobbies" id="hobbies" value="Music" />Music
<input type="checkbox" name="hobbies" id="hobbies" value="Swimming" />Swimming
<br /><br />
<label for="textarea">Address </label>
<br />
<textarea name="address" id="textarea" rows="15" cols="30"></textarea>
<span class="Error">*</span>
<br /><br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
PHP:
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
try {
$conn = new PDO("mysql:host=$servername;dbname=testing", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['submit'])){
$name = $_POST['name'];
$age = $_POST['age'];
$mailid = $_POST['mailid'];
$gender = $_POST['qualification'];
$hobbies = $_POST['address'];
if($name !='' || $mailid !='' || $address !=''){
$sql = "Insert into user (Name, Age, MailId, Gender, Qualification, Hobbies, Address)
values ('".$_POST["name"]."', '".$_POST["age"]."', '".$_POST["mailid"]."', '".$_POST["gender"]."', '".$_POST["qualification"]."', '".$_POST["hobbies"]."', '".$_POST["address"]."')";
$conn->exec($sql);
echo "Thank you for registering";
} else {
echo "<p>Insertion failed <br/> Please enter the required fields !";
}}
}
catch(PODException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
?>
Try adding the html 5 attribute "required" on all the required input elements. For example
<input type="text" Placeholder="Enter your name" name="name" id="name" required />
You should also check the POST variables in the php code though, as this doesn't really prevent someone from abusing your service. Ex.
if(!isset($_POST['somevar'])) {
// Do insert
}
In html You should use javascript (e.g. jQuery) to control onsubmit event and validate if mandatory fields are filled with proper values, check this link: jQuery.submit()
In php You should check and validate each var before create and execute query. Simple article about it is here: Sanitize and Validate Data with PHP Filters
This would be good for the start I think ;)
Query string should contain placeholders and then statement should be prepared for execution, check this link:
PDOStatement::bindParam
I've got some data posted to a php file, and I need to save/append that data separated by commas to a text file. That's all fine and dandy and should be straightforwards, except for when I check the file I see that every comma has been written twice: once where it needs to be, and then again after the appended data but as a group of commas.
Here's what I've got:
<form action="signup-submit.php" method="post">
<fieldset>
<legend>New User Signup:</legend>
<label>Name:</label>
<input type="text" name="name" size="16" autofocus required/> <br/>
<label>Gender:</label>
<label><input type="radio" name="gender" value="m" /> Male</label>
<label><input type="radio" name="gender" value="f" checked /> Female</label> <br />
<label>Age: <input type="text" name="age" size="6" maxlength="2" required></label><br/>
<label>Personality Type: <input type="text" name="pType" maxlength="4" size="6" required/></label><br/>
<label>
Favorite OS:
<select name="os">
<option value="windows">Windows</option>
<option value="mac">Mac OS X</option>
<option value="linux">Linux</option>
</select>
</label><br/>
<label>
Seeking age:
<input name="min" type="text" size="6" maxlength="2" placeholder="min" required/>
to
<input name="max" type="text" size="6" maxlength="2" placeholder="max" required/>
</label><br/>
<input type="submit" value="Sign up"/>
</fieldset>
</form>
^that code posts the "user data" to signup-submit.php where it is stored into variables by the same var names.
$name = $_POST["name"];
$age = $_POST["age"];
$gender = $_POST["gender"];
$pType = $_POST["pType"];
$os = $_POST["os"];
$min = $_POST["min"];
$max = $_POST["max"];
$c = chr(44);
$s = "$name$c$age$c$gender$c$pType$c$os$c$min$c$max";
file_put_contents("single.txt", $s, FILE_APPEND);
?>
and the text file will unfailingly duplicate the commas as such:
Byron,21,m,INTP,windows,18,23,,,,,,
the variables are simply data posted to this file from a previous page. I've also tried every which way under the sun to save the data. In fact, if I write only text directly, I get no problems. When I used the csv function I got just commas and no data despite or so I believed formatting it correctly.
That's probably because sometime all your variables are empty, and you FILE_APPEND just commas.
To solve this do:
if (!empty($name) && !empty($age) && ...) {
$s = "$name,$age,$gender,$pType,$os,$min,$max";
file_put_contents("single.txt", $s, FILE_APPEND);
}
If these values are user input always double check them. PHP offers standard functions to sanitize: Sanitize Filters, also you will need input validation with custom rules (for example to check if a variable is within a certain range, but this is a different question).