I have made this form where users can input various information,Everything is fine i am checking for different errors also but the problems is if user inputs email with a invalid email format and when pressing sumbit button it gives error invalid email format which is fine but mydatabase stores the invalid email also,How to prevent storing some invalid information?? And i am new to programming.
Thanks in advance.
$nameErr = $adressErr = $emailErr = $passwordErr = $genderErr = "";
$name = $adress = $email = $password = $gender = "";
if(isset($_POST['sumbit'])){
if (empty($_POST["name"])){
$nameErr = "Name is required";
}else{
$name = $_POST["name"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["adress"])){
$adressErr = "Adress is required";
}else{
$adress = $_POST["adress"];
}
if(empty($_POST["email"])){
$emailErr = "Email is required";
}else{
$email = $_POST["email"];
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if(empty($_POST["password"])){
$passwordErr = "Password is required";
}else{
$password = $_POST["password"];
}
if(empty($_POST["gender"])){
$genderErr = "Gender is required";
}else{
$gender = $_POST["gender"];
}
}
$sql = "INSERT INTO users(name,adress,email,password,gender)VALUES(:name,:adress,:email,:password,:gender)";
$statement = $conn->prepare($sql);
$statement->bindParam(":name",$name);
$statement->bindParam(":adress",$adress);
$statement->bindParam(":email",$email);
$statement->bindParam(":password",$password);
$statement->bindParam(":gender",$gender);
$statement->execute();
?>
Create a Boolean on top
$hasError = false;
In case of all error, set Boolean true as $hasError = true;
Before sql query :
if($hasError){
// redirect to form page -- pass the ERROR in the url as get and then show the error on form page
}
else{
// execute query code
}
It's good have server side checks, you can add a lot of validation on client side too.
Client side checks
For email, you can use type='email' instead of type='text'. Similarly, you can have maxlength, required, etc. to avoid erroneous data.
You first checked all field validation one by one and then executed your insert query. That's why always creating a new rows into database in both cases inputs are valid or invalid.
you should put your insertion query in the block if only inputs are valid.
Try this -
<?php
$nameErr = $adressErr = $emailErr = $passwordErr = $genderErr = "";
$name = $adress = $email = $password = $gender = "";
$error = array();
if(isset($_POST['sumbit'])){
if (empty($_POST["name"])){
$error[] = "Name is required";
}else{
$name = $_POST["name"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$error[] = "Only letters and white space allowed";
}
}
if(empty($_POST["adress"])){
$error[] = "Adress is required";
}else{
$error[] = $_POST["adress"];
}
if(empty($_POST["email"])){
$error[] = "Email is required";
}else{
$email = $_POST["email"];
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error[] = "Invalid email format";
}
}
if(empty($_POST["password"])){
$error[] = "Password is required";
}else{
$password = $_POST["password"];
}
if(empty($_POST["gender"])){
$error[] = "Gender is required";
}else{
$gender = $_POST["gender"];
}
}
if(empty($error)){
$sql = "INSERT INTO users(name,adress,email,password,gender)VALUES(:name,:adress,:email,:password,:gender)";
$statement = $conn->prepare($sql);
$statement->bindParam(":name",$name);
$statement->bindParam(":adress",$adress);
$statement->bindParam(":email",$email);
$statement->bindParam(":password",$password);
$statement->bindParam(":gender",$gender);
$statement->execute();
}else{
foreach ($error as $key => $value) {
echo '<li>'.$value.'</li>';
}
}
?>
Related
I am trying to figure out how to redirect after validation of a form (i.e after conditions for my form have been met)(I have the header at the end of the PHP code). I have a basic form ,and I know this should be a straightforward code of line but I can't seem to make it work! Your advice is very much appreciated!
<?php
$firstNameErr = '';
$lastNameErr = '';
$emailErr='';
$passwordErr = '';
$passwordConfErr='';
if($_SERVER["REQUEST_METHOD"] == "POST"){
$firstName = $_POST["firstName"];
if(empty($firstName)){
$firstNameErr = "First Name is required";
}
else if(!preg_match("/^[a-zA-Z]+$/", $firstName)){
$firstNameErr= "Only letters, no spaces or special characters allowed";
}
else{
$firstNameErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$lastName = $_POST["lastName"];
if(empty($lastName)){
$lastNameErr = "Last Name is required";
}
else if(!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $lastName)){
$lastNameErr = "No Special characters or numbers allowed";
}
else{
$lastNameErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email = $_POST["email"];
if(empty($email)){
$emailErr = "Email is required";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
else{
$emailErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$password=$_POST["password"];
if(empty($password)){
$passwordErr = "Please Enter your password";
}
else if (strlen($password) < "8") {
$passwordErr = "Your Password Must Contain At Least 8 Digits !";
}
else if(!preg_match("#[0-9]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Number !";
}
else if(!preg_match("#[A-Z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Capital Letter !";
}
else if(!preg_match("#[a-z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter !";
}
else if(!preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-]/', $password)) {
$passwordErr = "Your Password Must Contain At Least 1 Special Character !";
}
else{
$passwordErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$confirmPassword = $_POST["confirmPassword"];
$password = $_POST["password"];
if(empty($confirmPassword)){
$passwordConfErr = "Please Enter your password";
}
else if($password!=$confirmPassword){
$passwordConfErr = "Passwords do not match";
}
else{
$passwordConfErr="Valid";
}
}
else{
echo "Form not submitted with POST";
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST['Register']) and $firstNameErr == "Valid" and $lastNameErr =="Valid" and $emailErr == "Valid" and $passwordErr == "Valid" and $passwordConfErr=="Valid") {
header("Location: profile.php");
exit();
}
}
A single if ($_SERVER["REQUEST_METHOD"] == "POST"){ which wraps all $_POST logic would suffice, then depending on your app (if its mostly AJAX) you should use a response/request flow so the POST logic is at the top and it falls through to the view with the errors which can then be used in the view, or you should return JSON and do an AJAX request, else you won't be able to pick up the errors unless you put them into the session and then pick them up on redirect which is just extra steps.
Example request/response, for a single page i.e register.php, this could be broken out where you load the HTML via an include or view loader but the idea is the same.
<?php
$errors = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// first name
if (empty($_POST["firstName"])){
$errors['firstName'] = "First Name is required";
} else if (!preg_match("/^[a-zA-Z]+$/", $_POST["firstName"])) {
$errors['firstName'] = "Only letters, no spaces or special characters allowed";
}
// last name
if (empty($_POST["lastName"])) {
$errors['lastName'] = "Last Name is required";
} else if (!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $_POST["lastName"])) {
$errors['lastName'] = "No Special characters or numbers allowed";
}
// ...others
// errors is empty, so must all be valid
if (empty($errors)) {
// do something like insert into db and set session status
header("Location: profile.php");
exit();
}
// otherwise continue to form
} ?>
<form>
...
<input name="firstName" value="<?= htmlspecialchars($_POST['firstName'] ?? '', ENT_QUOTES, 'UTF-8') ?>"/>
<?= isset($errors['firstName']) ? '<span class="form-error">'.$errors['firstName'].'</span>' : '' ?>
<input name="lastName" value="<?= htmlspecialchars($_POST['lastName'] ?? '', ENT_QUOTES, 'UTF-8') ?>"/>
<?= isset($errors['lastName']) ? '<span class="form-error">'.$errors['lastName'].'</span>' : '' ?>
</form>
Or if your going to use mostly AJAX, another way would be to return JSON, then you can access the errors to then build out the dom from the AJAX response.
<?php
//
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
// set json response header
header('Content-type: application/json;charset=utf-8');
// Is POST
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//
$errors = [];
// first name
if (empty($_POST["firstName"])){
$errors['firstName'] = "First Name is required";
} else if (!preg_match("/^[a-zA-Z]+$/", $_POST["firstName"])) {
$errors['firstName'] = "Only letters, no spaces or special characters allowed";
}
// last name
if (empty($_POST["lastName"])) {
$errors['lastName'] = "Last Name is required";
} else if (!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $_POST["lastName"])) {
$errors['lastName'] = "No Special characters or numbers allowed";
}
// ...others
// errors is empty, so must all be valid
if (empty($errors)) {
// do something like insert into db and set session status
echo json_encode(['status' => 200]);
exit();
}
echo json_encode(['errors' => $errors]);
exit();
} else {
header($_SERVER["SERVER_PROTOCOL"]." 405 Method Not Allowed", true, 405);
echo json_encode(['status' => 405]);
}
} else {
header('Location: /');
}
In both examples, use a single errors array then its easy to access and all in one place. You also don't need to set additional vars from the $_POST['...'] vars to validate them.
Your validating code should look like this:
$Name = $Surname = $username = $password = $confirm_password =
$email ="";
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate Name.
if (empty(trim($_POST["firstName"]))) {
$errors[] = 'name required.';
} else {
$Name = $_POST["firstName"];
}
// Validate lastName.
if (empty(trim($_POST["lastName"]))) {
$errors[] = 'surname required.';
} else {
$Surname = $_POST["lastName"];
}
// Validate username
if (!preg_match("/^[a-zA-Z]+$/", $_POST["username"])) {
$errors['username'] = "Only letters, no spaces or special characters allowed";
}
// Validate username from database to see if username already exist.
//You can check for the email is well.
if(empty(trim($_POST["username"]))){
$errors[] = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM users WHERE username = :username";
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":username", $param_username, PDO::PARAM_STR);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() == 1){
$errors[] = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
$stmt->closeCursor();
}
}
// Validate password
if(empty(trim($_POST["password"]))){
$errors[] = "Enter password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$errors[] = "password should be min 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$errors[] = "confirm pass.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if($password != $confirm_password){
$errors[] = "pass no matches.";
}
}
// Validate Email
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$email = $_POST["email"];
} else {
$errors[] = "invalid email type.";
}
// Validate Email
if(empty(trim($_POST["email"]))){
$errors[] = 'email required.';
}else {
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
}
if(empty($errors)){
//if no errors
//Do everythin else in here
//Do insert query after you are done redirect to profile page
header("Location: profile.php");
exit();
}
}
To get eroors :
<?php if(isset($errors)) {?>
<div class="error">
<?php echo implode('<br/>', $errors); ?>
</div>
<?php } unset($_SESSION['errors']); ?>
And your html form here if its in same page :
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
//inputs etc..
</form>
I thought of using php header to redirect upon validation successful. However it's seems broken to me. How do I implement one then. Condition is when all the validation is validated then it would only redirect.
<?php
// define variables and set to empty values
$nameErr = $lastnameErr = $emailErr = $passwordErr = $confirmpasswordErr = $checkboxErr= "";
$name = $lastname = $email = $password = $confirmpassword = $checkbox = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$nameErr = "First Name is required";
}else {
$name = test_input($_POST["firstname"]);
}
if (empty($_POST["lastname"])) {
$lastnameErr = "Last Name is required";
}else {
$name = test_input($_POST["lastname"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
}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["password"]) && ($_POST["password"] == $_POST["confirmpassword"])) {
$password = test_input($_POST["password"]);
$confirmpassword = test_input($_POST["confirmpassword"]);
if (strlen($_POST["password"]) <= '8') {
$passwordErr = "Your Password Must Contain At Least 8 Characters!";
}
elseif(!preg_match("#[0-9]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Number!";
}
elseif(!preg_match("#[A-Z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Capital Letter!";
}
elseif(!preg_match("#[a-z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter!";
}
}
elseif(empty($_POST["password"])) {
$passwordErr = "Password not filled at all";
}
elseif(!empty($_POST["password"])) {
$confirmpasswordErr = "Password do not match";
}
if(!isset($_POST['checkbox'])){
$checkboxErr = "Please check the checkbox";
}
else {
$checkbox = test_input($_POST["checkbox"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
header('Location: http://www.example.com/');
Set $error = 1 if any condition get failed , and at the bottom check if($error!=1) then redirect
and you can also use javascript redirect if header is not working
Look at the closing "?>"-Tab. header will generate a html-header, but is a php-function and should be inside the ?php ?> bracket.
Consider using html5 input validation - saves some code and server roundtrips to let the browser do the validation
Omit the closing "?>" altogether. Its not necessary and can lead to hard to see errors when there is content - even blanks - after the "?>"
Consider using the filter_input function with appropriate parameters to access $_POST and set your variables.
I have a form which needs to be validated using php before inserting form values into a database.
it worked just fine if the fields are empty, however when I included a code to ensure only letters and white spaces are allowed in the first and last name fields it broke the validation process i.e. when I typed in any combinations of letters in the fields it displayed an error message saying "only letters and white spaces are required".
Secondly, when all fields are empty, the form displays the appropriate error message and does no submit the form to the database. However, when I type in a message in the textarea field with other fields empty, the form submits the data to the database as well as displays error messages for the other empty fields.
Any help to resolve these issues would be much appreciated.
Here is the code:
<?php
$fnameErr = $lnameErr = $emailErr = $amountErr = $phoneErr = $genderErr = $messageErr = $categoryErr = $countryErr = "";
$fname = $lname = $email = $amount = $phone = $gender = $message = $category = $country = "";
$ipaddress ="";
$defaultMessage = "Please type your message here.";
$formErrors = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//for first name
$name= $_POST["fname"];
if (empty($_POST["fname"])){
$fnameErr = "Please, enter your first name";
$formErrors = true;
}elseif(!preg_match("/^[a-zA-Z]*&/", $name)){
$fnameErr = "Only letters and white spaces are allowed in the first name field";
$formErrors = true;
}else{
$fname = $_POST["fname"];
$formErrors = false;
}
//Last Name match
// for last name
$name2= $_POST["lname"];
if (empty($_POST["lname"])){
$lnameErr = "Please, enter your last name";
$formErrors = true;
}elseif(!preg_match("/^[a-zA-Z]*&/", $name2)){
$lnameErr = "Only letters and white spaces are allowed in the Last name field";
$formErrors = true;
}else{
$lname = $_POST["lname"];
$formErrors = false;
}
// for email format
$emailf =($_POST["email"]);
if (empty($_POST["email"])) {
$emailErr = "Please, enter your email";
$formErrors = true;
}elseif (!filter_var($emailf, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
$formErrors = true;
}else {
$email = $_POST["email"];
$formErrors = false;
}
//for phone
if (empty($_POST["phone"])){
$phoneErr = "Please, enter your phone number";
$formErrors = true;
}else{
$phone = $_POST["phone"];
$formErrors = false;
}
// for amount
if (!isset($_POST["amount"])) {
$amountErr = "You must select an amount";
$formErrors = true;
}
else {
$amount = $_POST["amount"];
$formErrors = false;
}
// for gender
if (!isset($_POST["gender"])) {
$genderErr = "You must select your gender";
$formErrors = true;
}
else {
$gender = $_POST["gender"];
$formErrors = false;
}
// for country
if (empty($_POST["country"]) || $_POST["country"] == "Country") {
$countryErr = "Please, select your country";
$formErrors = true;
}
else {
$country = $_POST["country"];
$formErrors = false;
}
// for category
if (empty($_POST["category"]) || $_POST["category"] == "Category") {
$categoryErr = "Please, select a category";
$formErrors = true;
} else {
$category = $_POST["category"];
$formErrors = false;
}
// for message
if (empty($_POST["message"]) || $_POST["message"] == $defaultMessage){
$messageErr = "Please type your prayer request";
$formErrors = true;
}else{
$message = $_POST["message"];
$formErrors = false;
}
if (empty($formErrors) ) {
//connect to database
require_once("../../includes/connect_to_db.php");
// set time zone to uk
$timezone = date_default_timezone_set("Europe/london");
//setting values
$Timestamp = date('Y-m-d h:i:s');
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$gender = isset($_POST["gender"]) ? $_POST["gender"] : '';
$message = $_POST["message"];
$country = $_POST["country"];
$category = $_POST["category"];
//echo $gender . "value";
//var_dump(billingDate);
// var_dump($customer);
//Escape all string
$firstname = mysqli_real_escape_string($connection, $fname);
$lastname = mysqli_real_escape_string($connection, $lname);
$emailNew = mysqli_real_escape_string($connection, $email);
$phoneNew = mysqli_real_escape_string($connection, $phone);
$genderNew = mysqli_real_escape_string($connection, $gender);
$messageNew = mysqli_real_escape_string($connection, $message);
$countryNew = mysqli_real_escape_string($connection, $country);
$categoryNew = mysqli_real_escape_string($connection, $category);
//querying the database
$query = "INSERT into counselling ( ";
$query .= "Timestamp, FirstName, LastName, ";
$query .= "Email, PhoneNumber, Category, Country, Gender, Message";
$query .= ")";
$query .= "VALUES ('{$Timestamp}', '{$firstname}', '{$lastname}', ";
$query .= "'{$emailNew}', '{$phoneNew}', '{$categoryNew}', '{$countryNew}', '{$genderNew}', '{$messageNew}' ";
$query .= ")";
echo $query;
$result = mysqli_query($connection, $query) ;
//check for query error
if($result){
//query success redirect_to ("somepage.php");
//redirect_to("confirmation.php");
echo "Success";
} else {
die("Database query failed");
}
} // end of if
} // End of form submission conditional.
?>
Your need to refactor your code with proper logic.
<?php
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$errors = array();
if(trim($fname) == ''){
$errors['fname'] = "First name is required";
}
if(trim($lname) == ''){
$errors['lname'] = "Last name is required";
}
if(count( $errors) > 0){
//form invalid
}
else{
//form is valid
}
Okay, I tried once again, this time I removed the multiple php open/closing tags. So below is one big php chunk of code. If I fill out the form and send, the redirect works and I get the email - this all works great. The one last problem is the validation - I can submit empty fields and it redirects to the thankyou page - it doesn't warn users to fill out the fields...
So why now is the validation not working??? Thanks for your help guys.
<?php
// define variables and set to empty values
$fname = $lname = $email = $phone = $location = $size = $pvtype = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$company = test_input($_POST["company"]);
$fname = test_input($_POST["first-name"]);
$lname = test_input($_POST["last-name"]);
$email = test_input($_POST["email"]);
$phone = test_input($_POST["phone"]);
$address = test_input($_POST["address"]);
$city = test_input($_POST["city"]);
$provincestate = test_input($_POST["provincestate"]);
$country = test_input($_POST["country"]);
$location = test_input($_POST["location"]);
$size = test_input($_POST["size"]);
if(isset($_POST["type"])){ $type = $_POST['type'];}
$message = test_input ($_POST["message"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$companyErr = $fnameErr = $lnameErr = $emailErr = $phoneErr = $addressErr = $cityErr = $provincestateErr = $countryErr = $locationErr = $sizeErr = $typeErr = $messageErr ="";
$company = $fname = $lname = $email = $phone = $address = $city = $provincestate = $country = $location = $size = $type ="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["company"])) {
$company = "";
} else {
$company = test_input($_POST["company"]);
}
if (empty($_POST["first-name"])) {
$fnameErr = "First name is required";
} else {
$fname = test_input($_POST["first-name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["last-name"])) {
$lnameErr = "Last name is required";
} else {
$lname = test_input($_POST["last-name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$lnameErr = "Only letters allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} 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["phone"])) {
$phoneErr = "Phone number is required";
} else {
$phone = test_input($_POST["phone"]);
// check if phone number only contains 10 digits with no formatting
if (!preg_match("/^[0-9]{10}+$/",$phone)) {
$phoneErr = "Only enter a 10 digit number";
}
}
if (empty($_POST["address"])) {
$address = "";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["city"])) {
$city = "";
} else {
$city = test_input($_POST["city"]);
}
if (empty($_POST["provincestate"])) {
$provincestate = "";
} else {
$provincestate = test_input($_POST["provincestate"]);
}
if (empty($_POST["country"])) {
$country = "";
} else {
$country = test_input($_POST["country"]);
}
if (empty($_POST["location"])) {
$locationErr = "Location is required";
} else {
$location = test_input($_POST["location"]);
// check if location only contains letters
if (!preg_match("/^[a-zA-Z ]*$/",$location)) {
$locationErr = "Please enter a city";
}
}
if (empty($_POST["size"])) {
$sizeErr = "Please enter a number";
} else {
$size = test_input($_POST["size"]);
}
if (empty($_POST["type"])) {
$typeErr = "Please select 1";
} else {
$type = test_input($_POST["type"]);
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
}
$myemail = 'dgillison#sentinelsolar.com';//<-----Put Your email address here.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$to = $myemail;
$email_subject = "Inquiry from: $fname $lname";
$email_body = "You have received a new inquiry from:".
"\n
\n Name: $fname $lname \n Email: $email \n Phone Number: $phone
\n Address: $address \n City: $city \n Province/State: $provincestate \n Country: $country
\n I have a project in: $location \n The project type is: $type \n The estimated project size is: $size
\n Message: $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: thankyou.html');
exit();
}
?>
header() has to come before any output, so having it at the bottom will not work. Right now you don't really have an email 'function'. You can wrap that bottom piece of code into a sendEmail function. Then put the call to the function at the end of if ($_SERVER["REQUEST_METHOD"] == "POST") {.
You would have to pass all the variables in to the function. Or you could pass $_POST and do you variable cleaning in one function.
Move the email part up above the html, where it was redirecting automatically before. You need to add a check to see if there was a post request before sending the email and redirecting. Right after you set $myemail, there is an open bracket. Change this to:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
im trying to create a form that validates the input fields then sends the data into a mysql database. i can get either the input validation to work, or the data inserted into the database, but not both.. heres my code:
<?php require_once('../php/pdo_connect.php');
// define variables and set to empty values
$first_name_err = $last_name_err = $cell_err = $email_err = FALSE;
$first_name = $last_name = $cell = $email = FALSE;
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["first_name"]))
{$first_name_err = "First name is required";}
else
{
$first_name = test_input($_POST["first_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$first_name))
{
$first_name_err = "Please don't use hypens or other special characters";
}
}
if (empty($_POST["last_name"]))
{$last_name_err = "Last name is required";}
else
{
$last_name = test_input($_POST["last_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$last_name))
{
$last_name_err = "Please don't use hypens or other special characters";
}
}
if (empty($_POST["cell"]))
{$cell_err = "Phone number is required";}
else
{
$cell = test_input($_POST["cell"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[\+0-9\-\(\)\s]*$/",$cell))
{
$cell_err = "Invalid cell phone number";
}
}
if (empty($_POST["email"]))
{$email_err = "Email address is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$email_err = "Invalid email format";
}
}
if ($first_name_err = false){
//insert info into db
$query = $pdo->prepare("INSERT INTO `guestlist_page_requests` (first_name, last_name, cell, email) VALUES (?, ?, ? ,?)");
$query->bindValue(1, $first_name);
$query->bindValue(2, $last_name);
$query->bindValue(3, $cell);
$query->bindValue(4, $email);
$query->execute();
header('Location: ../index.php');
}else{
//not enough data to submit to db
}
}
i tried a few differant variations of this line:
if ($first_name_err = false){
but im not really sure what i should be putting here?
this line almost makes it work:
if (!empty($_POST['first_name']) && !empty($_POST['last_name']) && !empty($_POST['cell']) && !empty($_POST['email'])){
but then it submits the data with the errors unless one of the fields is empty.
this also doesnt seem to work right:
if ($first_name_err = false){