Right now, posting a snippet of what I wrote:
if (isset($_POST["email1"] != $_POST["email2"])) {
$email2Err = "please enter the same email address";
}
Every single time when I try to post the snippet above or a variation of it, it literally blanks out my page.
Question is, is the code I wrote above a good way to compare two email addresses via text fields?
And why does it blank out my entire page every time?
Here's a bit of further context if that's more helpful (let me know you want the entire page):
<?php
session_start(); //allows use of session variables
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["nights"])) {
$nightsErr = "# of nights are required";
} else {
$nights = test_input($_POST["nights"]);
}
if (empty($_POST["arrivals"])) {
$arrivalsErr = "Time of arrival is required";
} else {
$arrivals = test_input($_POST["arrivals"]);
}
if (empty($_POST["male"])) {
$maleErr = "# of people (gender female) required";
} else {
$male = test_input($_POST["male"]);
}
if (empty($_POST["female"])) {
$femaleErr = "# of people (gender female) required";
} else {
$female = test_input($_POST["female"]);
}
if (empty($_POST["rooms"])) {
$roomsErr = "# of rooms required";
} else {
$rooms = test_input($_POST["rooms"]);
}
if (empty($_POST["type"])) {
$typeErr = "type of rooms required";
} else {
$type = test_input($_POST["type"]);
}
if (empty($_POST["name"])) {
$nameErr = "name required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["address"])) {
$addressErr = "address required";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["zip"])) {
$zipErr = "zip required";
} else {
$zip = test_input($_POST["zip"]);
}
if (empty($_POST["telephone"])) {
$telephoneErr = "telephone required";
} else {
$telephone = test_input($_POST["telephone"]);
}
if (empty($_POST["email1"])) {
$email1Err = "email required";
} else {
$email1 = test_input($_POST["email1"]);
}
if (empty($_POST["email2"])) {
$email2Err = "email2 required";
} else {
$email2 = test_input($_POST["email2"]);
}
if (isset($_POST["email1"] != $_POST["email2"])) {
$email2Err = "please enter the same email address";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
This is failing you and isn't the right syntax for what you want to achieve:
if (isset($_POST["email1"] != $_POST["email2"]))
What you need to do is to first check if it is set then check if both are (not) equal to, but it's best to use !empty(), then check if it is not equal to:
if (!empty($_POST["email1"]) && !empty($_POST["email2"])) {
if ($_POST["email1"] != $_POST["email2"]) {
$email2Err = "Emails don't match. Please enter the same email address.";
}
}
Plus, make sure your form elements both have the right name attributes.
Also, a blank page can mean syntax errors.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
What you are doing is assigning by using a single equals to sign rather make it a double equals to sign, I mean ==
Try:
if (isset($_POST["email1"]) && isset($_POST["email2"])) {
if ($_POST["email1"] != $_POST["email2"]) {
$email2Err = "please enter the same email address";
}
}
Related
I want to check is the value exists in database but I always get false when I run the code below. can anyone please help me??
$key_in = $key_in_error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty(trim($_POST["key_in"]))) {
$key_in_error = "Please enter job number.";
}
// } else {
// $key_in = trim($_POST["key_in"]);
$key_in = mysqli_real_escape_string($link,$key_in); // SECURITY!
$result = mysqli_query($link,"SELECT * FROM files WHERE job_no='$key_in'");
if (mysqli_fetch_row($result)) {
header("location: downloads.php");
} else {
echo"Not valid job number!";
}
}
Try This
$key_in = $key_in_error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty(trim($_POST["key_in"]))) {
$key_in_error = "Please enter job number.";}
// } else {
// $key_in = trim($_POST["key_in"]);
$key_in = mysqli_real_escape_string($link,$key_in); // SECURITY!
$result = mysqli_query($link,"SELECT * FROM files WHERE job_no='$key_in'");
if (mysqli_num_rows($result)>0) {
header("location: downloads.php");
} else {
echo"Not valid job number!";
}
}
I am validating a form data using this script below.
When i submit the form if there is any errors the error message is displaying properly but if no errors and validation succeed i try to echo out the variables to test the script but the script is only displaying this : []
Please examine the code and help me solve this.
<?php
//included files
include("./includes/connect.php");
include("./includes/functions.php");
$errors = array();
//checking if user have submitted the form
if(isset($_POST['submitted'])) {
//validating and cleaning submitted form data ...
if (isset($_POST['name']) && !empty($_POST['name'])) {
if(preg_match("/^[a-zA-Z ]{2,20}$/", strip_trim($_POST['name']))) {
$cln_name = clean_data($_POST['name']);
} else {
$_POST['name'] = FALSE;
$errors[] = "The name you entered is not valid";
}
} else {
$errors[] = "You have not enter your name!";
}
if(isset($_POST['email']) && !empty($_POST['email'])) {
$cln_email = filter_var($_POST['email'] , FILTER_SANITIZE_EMAIL);
if(filter_var($cln_email, FILTER_VALIDATE_EMAIL)) {
$cln_email = clean_data($cln_email);
} else {
$_POST['email'] = FALSE;
$errors[] = "The email you entered is not valid";
}
} else {
$errors[] = "You have not provide you email!";
}
if(isset($_POST['plate_num']) && !empty($_POST['plate_num'])) {
if(ctype_alnum($_POST['plate_num']) && strlen($_POST['plate_num']) >= 5) {
$cln_plate_num = clean_data($_POST['plate_num']);
} else {
$_POST['plate_num'] = FALSE;
$errors[] = "The plate number you provided is not a valid plate number";
}
} else {
$errors[]= "You have not provide a plate number";
}
//checking for errors and printing errors..
if (count($errors > 0)) {
$errors_to_json = json_encode($errors);
echo $errors_to_json;
//foreach ($errors as $error) {
//echo $error . "<br />";
//}
} else {
echo $cln_name . "<br />";
echo $cln_email . "<br />";
echo $cln_plate_num;
}
} else {
echo "You did not submit the form!";
}
?>
This script is returning only this :
[]
Any idea please ??
functions.php :
<?php
function clean_data($data) {
if(function_exists('mysql_real_escape_string')) {
global $dbc;
$data = mysql_real_escape_string(trim($data), $dbc);
$data = strip_tags($data);
} else {
$data = mysql_escape_string(trim($data));
$data = strip_tags($data);
}
return $data;
}
function strip_trim($data) {
$data = stripslashes(trim($data));
return $data;
}
?>
you have problem in your if condition:
//checking for errors and printing errors..
if (count($errors > 0)) {
...
this will always return to TRUE because $error = [] and count([] > 0) results to TRUE
that's why you always end up in:
$errors_to_json = json_encode($errors);
echo $errors_to_json;
// Will indeed display '[]' because json_encode([]) is '[]'
i believe what you mean here is:
if (count($errors) > 0) {
...
I am trying to make a registration form and doing some checks before running SQL queries, but as i test and try to generate multiple errors, i am getting only the error that comes first, or sometimes no error at all. I am unable to locate where i have made error.
The following is the code in PHP.
//function to filter only phone numbers
function get_phone($number) {
return preg_replace('#[^0-9]#', '', $number);
}
//function to take only alphabets.
function get_alpha($alphabets){
return preg_replace('#[^a-z]#', '', $alphabets);
}
//function to check email.
function isValidEmail($email){
if (strlen ($email) > 50){
$errors[] = 'email address too long, please use a shorter email address..!';
} else {
return (filter_var($email, FILTER_VALIDATE_EMAIL));
}
}
function output_errors($errors){
$output = array();
foreach($errors as $error) {
$output[] = '<li>' . $error . '</li>';
}
return '<ul>' . implode('', $output) . '</ul>';
}
if (empty($_POST) === false) {
//store the text box field names of the form to local variables.
$cust_name = $_POST['name1'];
$cust_email = $_POST['email'];
$cust_phone = $_POST['phone'];
$cust_addr1 = $_POST['addr1'];
$cust_addr2 = $_POST['addr2'];
$cust_city = $_POST['city'];
$cust_state = $_POST['state'];
$cust_country = $_POST['country'];
$username = $_POST['uname'];
$password = $_POST['passwd'];
$cnf_passwd = $_POST['cnf_passwd'];
$sec_que = $_POST['sec_que'];
$sec_ans = $_POST['sec_ans'];
//sanitize the inputs from the users end.
$cust_name = sanitize($username);
$cust_phone = get_phone($cust_phone);
$cust_addr1 = sanitize($cust_addr1);
$cust_addr2 = sanitize($cust_addr2);
$cust_city = get_alpha($cust_city);
$cust_state = get_alpha($cust_state);
$cust_country = get_alpha($cust_country);
$username = sanitize($username);
$password = md5($password);
$cnf_passwd = md5($cnf_passwd);
$sec_que = sanitize($sec_que); //put up dropdown menu
$sec_ans = sanitize($sec_ans);
$cust_email = isValidEmail($cust_email);
//check for error handling in form data
//1. check for empty fields,
if ($cust_name == "" || $cust_phone == "" ||
$cust_addr1 == "" || $username == "" ||
$password == "" || $cnf_passwd == "" ||
$sec_que == "" || $sec_ans == ""
) {
$errors[] = 'No blank fields allowed, please fill out all the required fields..!';
//2.check for field lengths
} else if (strlen($cust_name) < 3 || strlen($cust_name > 20)) {
$errors[] = 'The name length should be between 3 to 20, please check & correct..!';
//3. check for phone number length
} else if (strlen($cust_phone) < 10 || strlen($cust_phone) > 11) {
$errors[] = 'The phone number must be 10 or 11 digits..!';
//4. check for address input lengths.
} else if (strlen($cust_addr1) < 5 || strlen($cust_addr1) > 50) {
$errors[] = 'Please provide a valid address..to serve you better..!';
//5. check if the password fields content match.
//length is not checked because the entered values will be converted to MD5 hash
// of 32 characters.
} else if ($password != $cnf_passwd) {
$errors[] = 'The passwords do not match. Please enter your passwords again..!';
// 6. check for length of the security answers.
} else if (strlen($sec_ans) < 5 || strlen($sec_ans) > 50) {
$errors[] = 'Please enter a proper security answer..!';
} //7. check for valid email address
else if($cust_email == false){
$errors[] = 'The email address you entered is not valid, please check and correct..!';
} else {
execute the SQL queries and enter the values in the database.
echo 'GOOD...TILL NOW..!!!';
}
} else {
$errors [] = 'No data received, Please try again..!!';
}
if(empty($errors) === false) {
?>
<h2>The Following errors were encountered:</h2>
<?php
echo output_errors($errors); //output the errors in an ordered way.
}
?>
When you use this structure:
if () {
} else if () {
} else if () {
}
// etc.
then only one condition can be satisfied. As soon as one of those if conditions is true, the rest of the else if blocks and the final else block are ignored.
If your conditions aren't mutually exclusive, put them in their own separate blocks:
if () {
}
if () {
}
if () {
}
// etc.
I'm trying to familiarize myself with PHP by making a simple pizza ordering system that emails size, toppings, and the orderer's information. The email sends nicely, but the toppings section of the email is blank. What am I missing?
Thanks!
<?php
/* Set e-mail recipient */
$myemail = "katrina.skovan#gmail.com";
$subject = "Pizza Order";
/* Check all form inputs using check_input function */
$name = check_input($_POST['name'], "Enter your name");
$email = check_input($_POST['email'], "Enter your email");
$street = check_input($_POST['street'], "Enter your your street");
$apt = check_input($_POST['apt'], "Enter your your apartment number");
$zip = check_input($_POST['zip'], "Enter your ZIP code");
$phone = check_input($_POST['phone'], "Enter your phone number");
$comments = $_POST['comments'];
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}
/* the following code is currently not working */
$pepperoni = $_POST['pepperoni'];
if(isset($_POST['pepperoni']) &&
$_POST['Pepperoni'] == 'Yes')
{
echo "pepperoni";
}
else
{
echo "";
}
if(isset($_POST['Half Pepperoni']) &&
$_POST['halfpepperoni'] == 'Yes')
{
echo "halfpepperoni";
}
else
{
echo "";
}
if(isset($_POST['Onions']) &&
$_POST['onions'] == 'Yes')
{
echo "onions";
}
else
{
echo "";
}
if(isset($_POST['Half Onions']) &&
$_POST['halfonions'] == 'Yes')
{
echo "halfonions";
}
else
{
echo "";
}
if(isset($_POST['Mushrooms']) &&
$_POST['mushrooms'] == 'Yes')
{
echo "mushrooms";
}
else
{
echo "";
}
if(isset($_POST['Half Mushrooms']) &&
$_POST['halfmushrooms'] == 'Yes')
{
echo "halfmushrooms";
}
else
{
echo "";
}
if(isset($_POST['Peppers']) &&
$_POST['peppers'] == 'Yes')
{
echo "peppers";
}
else
{
echo "";
}
if(isset($_POST['Half Peppers']) &&
$_POST['halfpeppers'] == 'Yes')
{
echo "halfpeppers";
}
else
{
echo "";
}
if(isset($_POST['Extra Cheese']) &&
$_POST['extracheese'] == 'Yes')
{
echo "extracheese";
}
else
{
echo "";
}
if(isset($_POST['Half Extra Cheese']) &&
$_POST['halfextracheese'] == 'Yes')
{
echo "halfextracheese";
}
else
{
echo "";
}
if(isset($_POST['Sausage']) &&
$_POST['sausage'] == 'Yes')
{
echo "sausage";
}
else
{
echo "";
}
if(isset($_POST['Half Sausage']) &&
$_POST['halfsausage'] == 'Yes')
{
echo "halfsausage";
}
else
{
echo "";
}
/* Let's prepare the message for the e-mail */
/* -=-=-=- EDITED -=-=-=- The toppings should be uncommented BUT you need to make variables like above Likewise the checkboxes need to have associated.
here's annother example variable:
$pepperoni = $_POST['pepperoni'];
*/
$message = "
Toppings:
$pepperoni
$halfpepperoni
$onions
$halfonions
$mushrooms
$halfmushrooms
$peppers
$halfpeppers
$extracheese
$halfextracheese
$sausage
$halfsausage
Name: $name
Email: $email
Street: $street
Apt: $apt
ZIP: $zip
Phone: $phone
Comments: $comments
";
$headers = "From:" . $email;
/* Send the message using mail() function */
/*mail($name, $email, $apt, $zip, $phone, $comments $pepperoni $halfpepperoni $onions $halfonions $mushrooms $halfmushrooms $peppers $halfpeppers $extracheese $halfextracheese $sausage $halfsausage);*/
mail($myemail,$subject,$message,$headers);
/* Redirect visitor to the thank you page */
header('Location: thanks.html');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>
</body>
</html>
<?php
exit();
}
?>
Replace all space between the textfield name, Ex: use halfonions instead of using textname with space like Half Onions
if(isset($_POST['halfonions']) && $_POST['halfonions'] == 'Yes') {
instead of
if(isset($_POST['Half Onions']) && $_POST['halfonions'] == 'Yes') {
You are not setting your variables, you are only echoing them out:
/* the following code is currently not working */
$pepperoni = $_POST['pepperoni'];
if(isset($_POST['pepperoni']) &&
$_POST['Pepperoni'] == 'Yes')
{
echo "pepperoni";
}
else
{
echo "";
}
Now the $pepperoni variable will contain Yes if it was selected and nothing else. And that is the only variable you are currently trying to set, the rest of the variables in your message is undefined.
You probably want something like:
if(isset($_POST['pepperoni']) &&
$_POST['pepperoni'] == 'Yes')
{
$pepperoni = "pepperoni";
}
else
{
$pepperoni = "";
}
And that for all the variables you use in your message.
And you can reduce that to:
$pepperoni = isset($_POST['pepperoni']) ? 'pepperoni' : '';
^ or however it is spelled in the html...
as the value does not really matter.
I think there are spaces in the variables like "Half Pepperoni" or "Half Mushrooms" !!
I would like to ask how do I set PHP "form validation" and "submit to database" in one single php file? This is what I tried to do in PART 1 and PART 2.
$latErr = $lngErr = $messageErr = "";
$lat = $lng = $message = "";
$tbl_name="stickers";
$datetime=date("d-m-y H:i:s");
//PART 1 - form validation method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["inputfield1"])) {
$latErr = "* Latitude is required. Please enable your browser geolocation settings.";
} else {
$lat = test_input($_POST["inputfield1"]);
}
if (empty($_POST["inputfield2"])) {
$lngErr = "* Longitude is required. Please enable your browser geolocation settings.";
}else{
$lng = test_input($_POST["inputfield2"]);
}
if (empty($_POST["message"])) {
$messageErr = "* Please enter your message.";
} else {
$message = test_input($_POST["message"]);
}
}
//PART 2 - check if all 3 parameters are filled, if yes then insert into database
if (isset($lat, $lng, $message)){
$sql="INSERT INTO $tbl_name(username, message, datetime, lat, lng )VALUES('$user- >username','$message', '$datetime', '$lat', '$lng')";
$result=mysql_query($sql);
//check if query successful
if($result){
$post_info = "Your msg is successfully posted!";
}else{
$post_info = "Oops, there is an error posting the msg.";
}
mysql_close();
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
It doesn't work. It just insert blanks into the database. Something is wrong but I dunno what is it? Anyone can advice. Thanks.
Maybe you need to use empty() instead of isset()?
//PART 1 - form validation method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["inputfield1"])) {
$latErr = "* Latitude is required. Please enable your browser geolocation settings.";
} else {
$lat = test_input($_POST["inputfield1"]);
}
if (empty($_POST["inputfield2"])) {
$lngErr = "* Longitude is required. Please enable your browser geolocation settings.";
}else{
$lng = test_input($_POST["inputfield2"]);
}
if (empty($_POST["message"])) {
$messageErr = "* Please enter your message.";
} else {
$message = test_input($_POST["message"]);
}
}
//PART 2 - check if all 3 parameters are filled, if yes then insert into database
if ( !empty($lat) && !empty($lng) && !empty($message) ){
$sql="INSERT INTO $tbl_name(username, message, datetime, lat, lng )VALUES('$user- >username','$message', '$datetime', '$lat', '$lng')";
$result=mysql_query($sql);
//check if query successful
if($result){
$post_info = "Your msg is successfully posted!";
}else{
$post_info = "Oops, there is an error posting the msg.";
}
}
else {
$post_info = "Empty content.";
}
mysql_close();