After reading a number of posts on here, on how to capture the Select values in my html form, I understand the principle but I cant seem to execute it flawlessly in my code below.
$selected_val isn't being appended. perhaps its empty? What am I missing? Thanks in advance.
Desired result:
test#test.com is an A-user ,
Current result:
test#test.com is an ,
Here is how my HTML form looks:
<form method="POST" class="subscription-form form-inline id="subscribe" role="form">
<h4 class="subscription-success"><i class="icon_check"></i> Thank you for requesting... </h4>
<h4 class="subscription-error">Something Wrong!</h4>
<select name="usertype" class="form-control input-box">
<option selected value="A-user">I'm an A user</option>
<option value="B-user">I'm an B user</option>
<option value="C-user">I'm an C user</option>
</select>
<input type="email" name="email" id="subscriber-email" placeholder="Your Email" class="form-control input-box">
<button type="submit" name="submit" id="subscribe-button" class="btn btn-default standard-button">Submit</button>
</form>
Here is my php:
<?php
if ( isset($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
$selected_val = $_POST['usertype']; // Storing Selected Value In Variable
$e_mail = $_POST['email'] . " is a " . $selected_val . " ," . "\n";
file_put_contents('email-list.txt', $e_mail, FILE_APPEND | LOCK_EX);
}
?>
Your form is missing method attribute
Post method should be there
<form action="your.php" method="post">
<form> element should have method attribute like
<form method="POST" class="subscription-form form-inline wow fadeInRight animated" data-wow-offset="10" data-wow-duration="1.5s" id="subscribe" role="form">
And NOTE in your PHP code, the user will click the submit button so check
if ( isset($_POST['submit'])) {
selected_val = $_POST['usertype']; // Storing Selected Value In Variable
$e_mail = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$e_mail = $e_mail . " - is a - " .$selected_val . " ," . "\n";
file_put_contents('email-list.txt', $e_mail, FILE_APPEND | LOCK_EX);
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I don't know what I did wrong on my code, the error message for php form validation stopped working.
It was working perfectly until i added value attribute to the input so that the user input will persist even if the page refresh and didn't deliver due to typeError.
The form does'nt show any error again but my reason for adding the value attribute is working.
I'm learning php, please help me to understand why i'm having the issue.
I don't understand because i'm not getting any error from php.
This is my code
<?php
// empting the value variables when user have'nt typed anything to prevent error. This is the shorthand of typing samething that's going to have the same value
$email = $title = $ingredients = '';
// put out the error on the html instead of echoing it
// so i used array so that i can neatly put out all the errors instead of using different variables for all
$error = array('email' => '', 'title' => '', 'ingredients' => '');
// check if the form was clicked and retrive the values sent
// i will achieve this by using a default method called isset() and i will check if value is contained in the form using the submit btn, this is because when a user clicks on the form submit, the user have entered a value
if(isset($_POST['submit'])){
// check if the field submited is empty
// we achieve this using a default method called empty()
// we check them one field at a time
// check for email
if(empty($_POST['email'])){
$error['email'] = ' Email is empty';
} else {
$email = $_POST['email'];
}
// check for title
if(empty($_POST['title'])){
$error['title'] = ' Title is empty';
} else {
$title = $_POST['title'];
}
// check for ingredients
if(empty($_POST['ingredients'])){
$error['ingredients'] = ' Ingredients is empty';
} else {
$ingredients = $_POST['ingredients'];
}
}
?>
<!DOCTYPE html>
<html lang="en">
<?php include 'template/header.php'?>
<form action="form.php" method="POST">
<div class="input_div">
<label >Email :</label>
<input type="text" name="email" value=" <?php echo $email ?> ">
<div class="error_msg"><?php echo $error['email']; ?></div>
</div>
<div class="input_div" >
<label >Pizza Title :</label>
<input type="text" name="title" value=" <?php echo $title ?> " >
<div class="error_msg"><?php echo $error['title']; ?></div>
</div>
<div class="input_div" >
<label >Ingredients (comma seperated) :</label>
<input type="text" name="ingredients" value=" <?php echo $ingredients ?> ">
<div class="error_msg"><?php echo $error['ingredients']; ?></div>
</div>
<div class="input_div" >
<input type="submit" class="submitBtn" name="submit" value="Submit">
</div>
</form>
<?php include 'template/footer.php' ?>
</html>
Other then the issues with whitespace in your inputs you should also be aware of XSS when inserting the values back into the form (like using " would break the form) and also don't populate the errors till needed, this will allow you to easily continue and do the success step without needing to loop over the $errors array and it also allows you to hide the <div class="error_msg"></div> element and only show when there is an error.
Also your missing <head> and <body>, presuming they are in the includes, but doing it that way would make it rather difficult to add additional elements or scripts.
<?php
$email = $title = $ingredients = '';
$error = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// check for email
if (empty($_POST['email'])) {
$error['email'] = 'Email is empty';
} else {
$email = $_POST['email'];
}
// check for title
if (empty($_POST['title'])) {
$error['title'] = 'Title is empty';
} else {
$title = $_POST['title'];
}
// check for ingredients
if (empty($_POST['ingredients'])) {
$error['ingredients'] = 'Ingredients is empty';
} else {
$ingredients = $_POST['ingredients'];
}
if (empty($error)) {
// do some thing with $email, $title, $ingredients
die(header('Location: ./thank-you.php'));
}
}
function xss_safe($value) {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
?><!DOCTYPE html>
<html lang="en">
<?php include 'template/header.php' ?>
<form action="form.php" method="POST">
<div class="input_div">
<label>Email :</label>
<input type="text" name="email" value="<?= xss_safe($email) ?>"/>
<?= isset($error['email']) ? '<div class="error_msg">'.$error['email'].'</div>' : '' ?>
</div>
<div class="input_div">
<label>Pizza Title :</label>
<input type="text" name="title" value="<?= xss_safe($title) ?>"/>
<?= isset($error['title']) ? '<div class="error_msg">'.$error['title'].'</div>' : '' ?>
</div>
<div class="input_div">
<label>Ingredients (comma seperated) :</label>
<input type="text" name="ingredients" value="<?= xss_safe($ingredients) ?>"/>
<?= isset($error['ingredients']) ? '<div class="error_msg">'.$error['ingredients'].'</div>' : '' ?>
</div>
<div class="input_div">
<input type="submit" class="submitBtn" name="submit" value="Submit">
</div>
</form>
<?php include 'template/footer.php' ?>
</html>
Seeing as your error checking is merely for empty/missed input fields it's easier to just make the inputs required as per HTML5. Here's a simplified version using placeholders for information after the form has been submitted.
Warning: If you are going to be inserting this data into a MySQL table, you need to sanitize the inputs first!
<?php
$email = $title = $ingredients = "";
if (isset($_POST["submit"])) {
$email = $_POST["email"];
$title = $_POST["title"];
$ingredients = $_POST["ingredients"];
}
echo "
<form method='POST'>
<label>Email:</label>
<input type='email' name='email' placeholder='$email' required>
<label>Pizza Title:</label>
<input type='text' name='title' placeholder='$title' required>
<label>Ingredients (comma seperated):</label>
<input type='text' name='ingredients' placeholder='$ingredients' required>
<input type='submit' name='submit' value='Submit'>
</form>
";
?>
I'm currently working on some webform.
This form is supposed to send collected data to txt file on webserver, but somehow it gives me error.
Form:
<form action="my_webserver_path_to_script.php" name="form" method="post">
<div>
<label for="name">Name</label>
<input name="name" type="text" id="name" placeholder="Your Name" required/>
</div>
<div>
<label for="city">City</label>
<input name="city" type="text" id="city" placeholder="Where do you live?" required/>
</div>
<div>
<label for="sex">Sex</label>
<select name="sex" id="sex" required>
<option value="" selected disabled hidden>Your sex</option>
<option value="man">Man</option>
<option value="woman">Woman</option>
</select>
</div>
<div style="margin-top: 30px; text-align: center;">
<input class="button" type="submit" value="Join Us!"/>
</div>
</form>
Script:
<?php
if(isset($_POST['name']) && isset($_POST['city']) && isset($_POST['sex'])) {
$data = $_POST['name'] . '-' . $_POST['city'] . '-' . $_POST['sex'] . "\n";
$ret = file_put_contents('my_webserver_path_to_data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
?>
When i fill all the fields and click submit it jumps to php address and prints 'There was an error writing this file'.
I've already read: questions/35443812 and questions/14998961
Usually, i don't respond between 16:00 and 08:00.
Thanks in advance!
The "file writing error" is mainly caused by an incorrect permissions setting in your hosting provider. Probably , you have to set up the 775 permission to write the file. This link could be useful for you https://unix.stackexchange.com/questions/35711/giving-php-permission-to-write-to-files-and-folders
About your PHP code. My suggestion is to improve the line #1 with the follow code:
<?php
if ( isset( $_POST['submit'] ) ) {
}
?>
Regards,
Ed.
simply type in the php $name= $_POST['name']; $city= $_POST['city']; $sex= $_POST['sex']; . If you type echo $name; you can see the data
I have a form as part of a custom plugin, but it is not retaining the data when submitted. It saves in the database, and if I refresh the page it shows the information, but I want it to stay in the form first time.
I know it must be something really stupid, I just don't seem to find it... Thanks in advance!
This is the code:
<?php
global $guarantor_details;
add_shortcode('guarantorForm', 'guarantor_form');
function guarantor_form()
{
$output = "";
global $current_user;
$current_user = wp_get_current_user();
$guarantor_details = getGuarantorData();
$message = (isset($_POST["guarantor_save"])) ? saveGuarantor() : false;
if ($message) $output .= '<div class="success">' . $message . '</div>';
$message = (isset($_GET["resend"]) == "true") ? generateGuarantorEmail($guarantor_details) : false;
if ($message) $output .= '<div class="success">' . $message . '</div>';
if($current_user->ID){
$output .= '
<h1>Guarantor Details</h1>
<form action="" method="POST" class="profileForm">
<div class="formField">
<label for="guarantor_title">Title</label>
<select name="guarantor_title">
<option value="Mr">Mr</option>
<option value="Miss">Miss</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
</select>
</div>
<div class="formField">
<label for="guarantor_name">Guarantor Full Name</label>
<input name="guarantor_name" type="text" required
value="' . $guarantor_details->guarantor_name . '"/>
</div>
<div class="formField">
<label for="guarantor_relationship">Relationship to student</label>
<input name="guarantor_relationship" type="text" required
value="' . $guarantor_details->guarantor_relationship . '"/>
</div>
<div class="formField">
<label for="guarantor_address1">Address 1</label>
<input name="guarantor_address1" type="text" required
value="' . $guarantor_details->guarantor_address1 . '"/>
</div>
<div class="formField">
<label for="guarantor_address2">Address 2</label>
<input name="guarantor_address2" type="text" value="' . $guarantor_details->guarantor_address2 . '"/>
</div>
<div class="formField">
<label for="guarantor_city">City</label>
<input name="guarantor_city" type="text" required
value="' . $guarantor_details->guarantor_city . '"/>
</div>
<div class="formField">
<label for="guarantor_county">County</label>
<input name="guarantor_county" type="text" required
value="' . $guarantor_details->guarantor_county . '"/>
</div>
<div class="formField">
<label for="guarantor_postcode">Postcode</label>
<input name="guarantor_postcode" type="text" required
value="' . $guarantor_details->guarantor_postcode . '"/>
</div>
<div class="formField">
<label for="guarantor_country">Country</label>
<select name="guarantor_country">
' . countryList() . '
</div>
<div class="formField">
<label for="guarantor_mobile">Mobile</label>
<input name="guarantor_mobile" type="tel" required
value="' . $guarantor_details->guarantor_mobile . '"/>
</div>
<div class="formField">
<label for="guarantor_confirm_mobile">Confirm Mobile</label>
<input name="guarantor_confirm_mobile" id="confirm_mobile" type="tel" required value="' . $guarantor_details->guarantor_mobile . '"/>
</div>
<div class="formField">
<label for="guarantor_telephone">Telephone</label>
<input name="guarantor_telephone" type="tel" required
value="' . $guarantor_details->guarantor_telephone . '"/>
</div>
<div class="formField">
<label for="guarantor_email">Email</label>
<input name="guarantor_email" type="email" required
value="' . $guarantor_details->guarantor_email . '"/>
</div>
<div class="formField">
<input name="guarantor_save" type="submit" value="Save"/>
</div>
<div class="formField alignRight">
Lost the email with the link? Resend Email
</div>
</form>
';}
else{
$output = 'You must login to fill in guarantor details.';
}
return $output;
}
function getGuarantorData()
{
global $current_user;
global $wpdb;
$table = $wpdb->prefix . 'vebra_tenants';
$guarantor_details = $wpdb->get_row(
"
SELECT *
FROM $table
WHERE tenant_user_id = $current_user->ID
"
);
return isset($guarantor_details) ? $guarantor_details : false;
return $guarantor_details;
}
//save guarantor details
function saveGuarantor()
{
global $wpdb;
global $current_user;
$guarantor_details = getGuarantorData();
$details = $_POST;
unset($details["guarantor_save"]); //no submit
unset($details["guarantor_confirm_mobile"]); //no submit
if ($guarantor_details) {
$wpdb->update(
$wpdb->prefix . 'vebra_tenants',
$details,
array('tenant_user_id' => $current_user->ID));
} else {
$details['tenant_user_id'] = $current_user->ID;
$wpdb->insert($wpdb->prefix . 'vebra_tenants', $details);
$guarantor_details = getGuarantorData();
}
//let db know details updated
update_user_meta($current_user->ID, 'vebra_guarantor_details', true );
//send email if not already sent
if ($guarantor_details->guarantor_hash == "") {
generateGuarantorEmail($guarantor_details);
return "The guarantor details have been saved and an email has been sent to your guarantor to accept the agreement. They have seven days to respond.";
}
//set status percentage of that property
$pcode = get_user_meta($current_user->ID, 'vebra_pcode', true);
saveStatusProgress($pcode);
return "The guarantor details have been saved";
}
function generateGuarantorEmail($guarantor_details)
{
global $current_user;
global $wpdb;
$code = md5($guarantor_details->guarantor_name);
$wpdb->update($wpdb->prefix . 'vebra_tenants',
array('guarantor_hash' => $code,
'guarantor_sent' => date('Y-m-d h:m:s')),
array('tenant_user_id' => $current_user->ID,
));
$message = "Hello " . $guarantor_details->guarantor_name . "\n\n";
$message .= "Your name has been listed as a guarantor for a student let for " . $guarantor_details->tenant_firstname . " " . $guarantor_details->tenant_surname;
$message .= "\n\nIf you have agreed to being the guarantor, please click on the link below to go to a secure area of our website. There you will find a copy of the Assured Tenancy Agreement for the property, and the guarantor form. Please print off the guarantor form, sign and have it witnessed and then return it to us as soon as you can.";
$message .= "\n\n" . get_permalink(get_option('vebra_confirmPermalink')) . "?confirm=" . $guarantor_details->guarantor_hash;
$message .= "\n\n If you have not agreed to being a guarantor, would you please email us to let us know.";
$message .= "\n\n Thank you for your help.\n\n \n\n";
sendEmailToPublic($guarantor_details->guarantor_email, ' ', 'Guarantor Proposal', $message);
return "An email has been sent to the guarantor with a link for them to activate and accept to be a guarantor";
}
You might not getting database stored values inside $guarantor_details object.
so please check are you getting something in $guarantor_details->guarantor_name
if not then try to resolve it,
OR
If you just want to display submitted data then, you can simply print the post data in your case for guarantor_mobile its
<input name="guarantor_mobile" type="tel" required value="'. $_POST["guarantor_mobile"].'"/>
Thanks for the answers, but I solved this in a different way, had to load $guarantor_details = getGuarantorData(); just before building the form to make sure the data was displayed correctly.
I'm trying to do simple script with PHP and insert some data, but nothing happens! I knew that I missed something but what is it?
This my code:
<?php
$host= "localhost";
$user="root";
$pass="freedoom19";
$db="dddd";
$con = mysqli_connect($host,$user,$pass,$db) or mysql_error();
//====== Get Variable======= //
$name = $_POST['name'];
$email=$_POST['email'];
$rate=$_POST['select_style'];
$content=$_POST['content'];
$insert="insert into reviews (name,email,rate,content) values ('$name','$email','$rate','$content')";
//====== Get Variable======= //
if($_POST['submit-comment']) {
if($name && $email && $content == true) {
mysqli_query($con,$insert);
$success = "<span class='success_testmonial'>Thank You! .. Your Raiting Has Been Submitted And We Will Post It As Soon We Verify It !</span>";
}
else {
$error = "<span class='error_testmonial'>Error : one or some fields has left empty .. Please fill all field and try again.</span>";
}
}
mysqli_close($con);
?>
And this it the form and the "action" ..
<form method="post" action="" id="form-contact" class="clearfix">
<div id="form-left">
<label for="text-name">Name *</label><br />
<input type="text" name="name" class="input" id="text-name" /><br />
<label for="text-email">From *</label><br />
<input type="text" name="email" class="input" id="text-email" /><br />
<label for="text-phone">Rate us *</label><br />
<div class="select-style">
<select>
<option value="5.0">5.0</option>
<option value="4.5">4.5</option>
<option value="4.0">4.0</option>
<option value="3.5">3.5</option>
<option value="3.0">3.0</option>
<option value="2.5">2.5</option>
<option value="2.0">2.0</option>
<option value="2.0">2.0</option>
<option value="1.5">1.5</option>
<option value="1.0">1.0</option>
</select>
</div>
</div>
<div id="form-right">
<label for="text-comment">Review <span></span></label><br />
<textarea name="content" cols="10" rows="20" class="input textarea" id="text-comment"></textarea><br />
<input type="submit" name="submit-comment" class="button" value="Rate Us" />
</div>
<p id="text-contact">
<br><br><font color="#980303">Please Note *</font> Thate Your Reviews Will Not Published Untill We Check it and sure that the review don't contain Bad words or bad language, and be sure that we will publish all reviews and we accept criticism!
</form>
So what I missed please?
Check this working code. Also you had not set element name for Drop down as select_style. It was throwing error for that too.
PHP Code
if(isset($_POST['submit-comment']) && $_POST['submit-comment']!='') {
$host= "localhost";
$user="root";
$pass="";
$db="test";
$con = mysqli_connect($host,$user,$pass,$db) or mysql_error();
//====== Get Variable======= //
$name = mysqli_real_escape_string($con,$_POST['name']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$rate = mysqli_real_escape_string($con,$_POST['select_style']);
$content = mysqli_real_escape_string($con,$_POST['content']);
$insert="insert into reviews (name,email,rate,content) values ('$name','$email','$rate','$content')";
if($name && $email && $content == true) {
mysqli_query($con,$insert);
$success = "<span class='success_testmonial'>Thank You! .. Your Raiting Has Been Submitted And We Will Post It As Soon We Verify It !</span>";
echo $success;
}
else {
$error = "<span class='error_testmonial'>Error : one or some fields has left empty .. Please fill all field and try again.</span>";
echo $error;
}
mysqli_close($con);
}
HTML
<form method="post" action="" id="form-contact" class="clearfix">
<div id="form-left">
<label for="text-name">Name *</label><br />
<input type="text" name="name" class="input" id="text-name" /><br />
<label for="text-email">From *</label><br />
<input type="text" name="email" class="input" id="text-email" /><br />
<label for="text-phone">Rate us *</label><br />
<div class="select-style">
<select name="select_style">
<option value="5.0">5.0</option>
<option value="4.5">4.5</option>
<option value="4.0">4.0</option>
<option value="3.5">3.5</option>
<option value="3.0">3.0</option>
<option value="2.5">2.5</option>
<option value="2.0">2.0</option>
<option value="2.0">2.0</option>
<option value="1.5">1.5</option>
<option value="1.0">1.0</option>
</select>
</div>
</div>
<div id="form-right">
<label for="text-comment">Review <span></span></label><br />
<textarea name="content" cols="10" rows="20" class="input textarea" id="text-comment"></textarea><br />
<input type="submit" name="submit-comment" class="button" value="Rate Us" />
</div>
<p id="text-contact">
<br><br><font color="#980303">Please Note *</font> Thate Your Reviews Will Not Published Untill We Check it and sure that the review don't contain Bad words or bad language, and be sure that we will publish all reviews and we accept criticism!
</form>
try to put your get variables inside the if else statement
check if there are datas in POST when done submitting:
if($_POST['submit-comment']) {
$name = $_POST['name'];
$email=$_POST['email'];
$rate=$_POST['select_style'];
$content=$_POST['content'];
$insert="insert into reviews (name,email,rate,content) values ('$name','$email','$rate','$content')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
var_dump($_POST);
}
$con->close();
check for errors:
$check = mysqli_query($con,$insert);
var_dump($check);
if you found one, let me know
Note:
Put your insert query and passed on variables (POST) inside your if statement isset(POST["submit-comment"] to eliminate errors of undefined variables.
You should use mysqli_* prepared statement instead to prevent SQL injections.
Answer:
If you insist on retaining your code, you can use mysqli_real_escape_string() function to fertilize a bit the content of your variables before using it in your query.
Your PHP file should look like this:
<?php
$host= "localhost";
$user="root";
$pass="freedoom19";
$db="cookindoor";
$con = mysqli_connect($host,$user,$pass,$db) or mysql_error();
//====== IF SUBMIT-COMMENT ======= //
if(isset($_POST['submit-comment'])) {
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["content"])) {
//====== GET VARIABLES ======= //
$name = mysqli_real_escape_string($con,$_POST['name']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$rate = mysqli_real_escape_string($con,$_POST['select_style']);
$content = mysqli_real_escape_string($con,$_POST['content']);
$insert="INSERT INTO reviews (name,email,rate,content) VALUES ('$name','$email','$rate','$content')";
mysqli_query($con,$insert);
$success = "<span class='success_testmonial'>Thank You! .. Your Raiting Has Been Submitted And We Will Post It As Soon We Verify It !</span>";
}
else {
$error = "<span class='error_testmonial'>Error : one or some fields has left empty .. Please fill all field and try again.</span>";
}
}
mysqli_close($con);
?>
Recommendation:
But if you execute it in mysqli_* prepared statement, your insert query would look like this. Though this is just a simple example but still executable:
if($stmt = $con->prepare("INSERT INTO reviews (name, email, rate, content) VALUES (?,?,?,?)")){ /* CHECK THE QUERY */
$stmt->bind_param('ssss', $_POST["name"], $_POST["email"], $_POST["rate"], $_POST["content"]); /* BIND VARIABLES TO YOUR QUERY */
$stmt->execute(); /* EXECUTE YOUR QUERY */
$stmt->close(); /* CLOSE YOUR QUERY */
}
This question already has an answer here:
How to validate form in php
(1 answer)
Closed 8 years ago.
Anyone please help me on how to validate a form? I have the code, it is working ok..but I found that after I hit the submit button & php shows the errors, there is an input field, asking the user to answer the math Ques..when I enter the answer, then hit submit button again, it just says mail successfully sent, but other fields are still empty. Any ideas how to fix it. Also, the php value in the answerbox input tags, is not saving the text in box, it disappears. by the way, I got some help from other users, i'm a noob in php, so if you don't mind please explain.
Thanks for your time!
<form name="contact" action="formtest.php" method="post">
<label for="YourName">Your Name:</label>
<input type="text" name="name" class="required" value="<?= isset($_POST['name']) ? $_POST['name'] : '' ?>" />
<label for="YourEmail">Your Email:</label>
<input type="text" name="email" class="required" value="<?= isset($_POST['email']) ? $_POST['email'] : '' ?>"/>
<label for="Subject">Subject:</label>
<input type="text" name="subject" class="required" value="<?= isset($_POST['subject']) ? $_POST['subject'] : '' ?>" />
<label for="YourMessage">Your Message:</label>
<textarea name="message" class="required"><?= isset($_POST['message']) ? $_POST['message'] : '' ?></textarea>
<p class="c3">10 + 5 =<input type="text" name="answerbox" id="answerbox" "<?= isset($_POST['answerbox']) ? $_POST['answerbox'] : '' ?>"/></p>
<fieldset>
<input type="submit" name="submit" id="submit" value="Send" class="required"/>
<input type="reset" id="reset" value="Reset"/>
</fieldset>
<?php
if(isset($_POST['submit'])){
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$subject = trim($_POST["subject"]);
$message = trim($_POST["message"]);
$answerbox = trim($_POST["answerbox"]);
if(empty($_POST['name'])){
print "<div class='formerrors'><li>Please type your name.</li></div>";
}
else {
if (ctype_alpha($name) === false) {
print "<div class='formerrors'><li>Your name only should be in letters!</li></div>";
}
}
if(empty($_POST['email'])){
print "<div class='formerrors'><li>You've forgot to type your email address.</li></div>";
} else{
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
print "<div class='formerrors'><li>Your email is not valid, please check.</li></div>";
}
}
if(empty($_POST['subject'])){
print "<div class='formerrors'><li>Please type a subject.</li></div>";
}
if(empty($_POST['message'])){
print "<div class='formerrors'><li>You've forgot to type your message.</li></div>";
}
if(empty($_POST['answerbox'])){
print "<div class='formerrors'><li>Please answer the math question.</li></div>";
}
else {
if($answerbox != 15){
print"<div class='formerrors'><li>Answer is not correct.</li></div>";
}
else{
$headers = 'From: '.$email. "\r\n" .
'Reply-To: '.$email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail('me#mymail.me',$subject,$message,$headers);
print "<div class='formerrors'><li>mail succesuffully sent</li></div>";
}
}
}
?>
</form>
Try placing your php code above the html as it is php setting the values of the variables, and you are calling them before they are set.
It is best practice to have php code at the top of the file, and then html below it, or even have the php on a separate file, but include it at the top.
Also I find it better to create an array of errors, and then if the array count is 0, then perform the action (send email) else call the error of arrays within the html, not the php. Then you can choose where to display it on the page, and style it accordingly.
Change your form action to
<?php $PHP_SELF; ?>
So it has to be
<form name="contact" action="<?php $PHP_SELF; ?>" method="post">
For the other issue you must place your code above the form.