I've got the following line of code in PHP at the top of the page making sure all form fields have content in them and not submitted empty...
if(!isset($_POST['name'])) { $err_name = 1; }
if (!isset($_POST['phone'])) { $err_phone = 1; }
if (!isset($_POST['email'])) { $err_email = 1; }
if ((!isset($_POST['serve'])) && ($_POST['other'] == "")) { $err_serve = 1; }
name is a text input
email is a text input
phone is a text input
serve is a checkbox array
other is a text input
Then below that I've got the following lines which allow the php code to continue if there are no errors (above)
if (($err_name != 1) && ($err_phone != 1) && ($err_email != 1) && ($err_serve != 1)) {
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$phone = $_POST['phone']; // required
$serve = $_POST['serve'];
$other = $_POST['other'];
Then I've got this next to each form field...
<?php if ($err_name == 1) { echo '<font color="red">Name cannot be empty</font>'; } ?>
<?php if ($err_phone == 1) { echo '<br /><font color="red">Phone cannot be empty</font>'; } ?>
<?php if ($err_email == 1) { echo '<font color="red">Email cannot be empty</font>'; } ?>
<?php if($err_serve == 1) { echo '<br /><font color="red">You must choose at least 1 area to serve</font>'; } ?>
Can someone please help me figure out WHY its doing the following...
if I take && ($err_serve != 1) out of the 2nd code, everything
except phone shows error messages
if I leave it in, ONLY err_serve throws error. The others are
ignored and no error is displayed.
Phone refuses to throw error messages. This is everything where $_POST
handling is in the php.
Note that all tests are done by submitting a completely empty form
The values will be set whether or not they are filled with a value. If it's an empty value, it's still a value.
Instead of using isset(), use empty(). It checks both if:
The value exists at all
The value is something other than 0, an empty string, false, etc.
The reason it works for the checkbox, is because when a checkbox is not checked, the browser does not send the value at all. This is contrary to text fields. A browser will send the value of a text field whether or not it's empty.
http://ca2.php.net/manual/en/function.empty.php
Related
I am currently making a self-processing form to display products that allows users to enter a quantity. I will then save the quantity in
$_POST['qty_entered']
when the users press the submit button. However, I also have an if statement to ensure that the users entered a valid quantity
if (is_numeric($_POST['qty_entered'][0]) && is_int($_POST['qty_entered'][0]) && $_POST['qty_entered'][0] > 0) {
print "'<tr><td>' test '</td>'";
}
else {
$errors = true}
Then want to print a table with the invoice on the same page, only after the submit button is pressed and if the user entered a valid quantity. However, this code is not working:
if (array_key_exists ('submit_button', $_POST)) && $errors = false{
print "Invoice";
I also have a code at the beginning of the form to set $errors to false, and if $errors is true, it will print an error message. However, it is also not working because it doesn't display the error message when I type rubbish that would trigger the if statement such as "agfasgs" or "-1"
$errors = false;
if ($errors == true) {
print "Please enter postive whole numbers for quantity <br><br>";}
Thank you for the help!
This line does not have the brackets properly inserted. Also you need == or ===(This enforces strict check) What you have currently assigns the variable. You need to check.
The === operator is supposed to compare exact content equality while the == operator would compare semantic equality
if (array_key_exists ('submit_button', $_POST)) && $errors = false{//This should have thrown an error though(FATAL)
It should be
if (array_key_exists ('submit_button', $_POST) && $errors == false){
Also, FYI, shouldnt this line
if (is_numeric($_POST['qty_entered'][0]) && is_int($_POST['qty_entered'][0]) && $_POST['qty_entered'][0] > 0) {
Be this: ?
if (is_numeric($_POST['qty_entered']) && is_int($_POST['qty_entered']) && $_POST['qty_entered'] > 0) {//access the post data properly
php
if (array_key_exists ('submit_button', $_POST)) && $errors = false{
print "Invoice";
is not valid PHP: Your parens are wrong, and you're assigning false to $errors (you want ==, not =)
if (array_key_exists('submit_button', $_POST) && $errors == false) {
I am learning how to code PHP and I have two pages: rates.html and rates.php. Our assignment has it so that we only need to run rates.php and will no longer need to use rates.html. My way of going around this problem is as follows:
if (empty($_POST['txtInput'])){
$inputCurrency = 0;
$outputCurrency = 0;
$txtInput = '';
} else {
$inputCurrency = $_POST['inputCurrency'];
$outputCurrency = $_POST['outputCurrency'];
$txtInput = $_POST['txtInput'];
}
Input and output currencies are made in the form of a drop down list, and txtInput is the number that the user wants to convert.
The only problem with this is that my page throws up an error message when a user submits a form without any input in the field. The page loads the following code:
if ( empty($txtInput) ) {
$error_message = 'Input is a required field.'; }
else if ( !is_numeric($txtInput) ) {
$error_message = 'Input must be a valid number.'; }
else if ( $txtInput <= 0 ) {
$error_message = 'Input must be greater than zero.'; }
else {
$error_message = ''; }
Is there a way for the flag to not be thrown up on the pages first load? Any help would be appreciated
Wrap your logic that should only run when a form is submitted in an if block that checks to see if the form is submitted via POST:
if ('POST' === $_SERVER['REQUEST_METHOD']) {
// Form submitted. Put form logic here.
}
I'm trying to create a dynamic if-statement. The reason I want to do this, is because I need to check server-sided whether inputfields match my regex and are not empty. However, some of my inputfields can be removed in my CMS, meaning there would be more/less inputfields accordingly.
Ideally I would add variables in my if-statement but I'm not 100% sure if that's allowed, so perhaps I would need an other way to solve this problem. Here's what I tried:
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
$cstreetname = " || $_POST['streetname'] == ''"; //Used to check if field is empty
$pstreetname = " || !preg_match($streetnameReg,$_POST['streetname'])"; //Used to check if it matches my regex
}
else
{
//These variables define variables if inputfields are not shown
$streetname= ''; //No streetname means it's excluded in INSERT query
$cstreetname = ''; //Not needed in check
$pstreetname = ''; //Also not needed in check
}
// more of these if/else statements
if ($_POST['firstname'] == '' || $_POST['lastname'] == '' || $_POST['email'] == '' $cstreetname $cpostalcode $chometown $ctelnr $csex $cdateofbirth)
{
echo 'One of the fields is empty.';
header('refresh:3;url=index.php');
}
else
{
//Regex check, after that more code
}
My idea was to check if a specific field is shown on the front-end and in that case I'm creating some variables that I want to paste in my if-statements.
I'm getting an error saying Server error meaning my php-code would be invalid.
Is it even possible at all to make a dynamic if-statement? If yes, at what part am I failing?
Help is much appreciated! Thanks in advance.
First of all, since it looks like you need to combine all of the conditionals with ||, you can correct your program by writing it like this:
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
$cstreetname = $_POST['streetname'] == ''; //Used to check if field is empty
$pstreetname = !preg_match($streetnameReg,$_POST['streetname']); //Used to check if it matches my regex
}
else
{
//These variables define variables if inputfields are not shown
$streetname= ''; //No streetname means it's excluded in INSERT query
$cstreetname = false; //Not needed in check
$pstreetname = false; //Also not needed in check
}
if ($_POST['firstname'] == '' || $_POST['lastname'] == '' || $_POST['email'] == '' || $cstreetname || $cpostalcode || $chometown || $ctelnr || $csex || $cdateofbirth)
{
echo 'One of the fields is empty.';
header('refresh:3;url=index.php');
}
This would work, but it's unwieldy. A much better solution would be to use an array (let's name it $errors that gets dynamically populated with errors resulting from validating your fields. Like this:
$errors = array();
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
if ($streetname == '') {
$errors[] = 'Streetname cannot be empty.'; // message is optional
}
if (!preg_match($streetnameReg,$streetname)) {
$errors[] = 'Streetname is invalid.'; // message is optional
}
}
And then:
if ($errors) {
echo 'There are errors with the data you submitted.';
header('refresh:3;url=index.php');
}
If you provided human-readable error messages you can also arrange for them to be displayed so that the user knows what they need to fix. And of course there are lots of variations of this technique you can use -- e.g. group the error messages by field so that you only show one error for each field.
If you want to check for empty $_POST fields you can do something like this
$error = False;
foreach($_POST as $k => $v)
{
if(empty($v))
{
$error .= "Field " . $k . " is empty\n";
}
}
if(!$error)
{
echo "We don't have any errrors, proceed with code";
}
else
{
echo "Ops we have empty fields.\n";
echo $error;
}
And after you are sure that all the fields are not empty you can do other stuff.
I've a form,in the form only few fields are mandatory.When a fields is not mandatory,it should not check for empty data validation.If the non mandatory field contain data then it shoudl check the data,validation should happen only when data present.
My below code check for all fields.For eg:Say phone is not mandatory in below code,how to change the code.
$validate = array(
array($x, '/^[a-z\d ]{4,20}$/i', "Please enter valid name."),
array($y, '/^[a-z\d ]{4,20}$/i', "Please enter a real category."),
array($phone, '/^\(?[0-9]{3}\)?|[0-9]{3}[-. ]? [0-9]{3}[-. ]?[0-9]{4}$/' , "Please enter a valid phone number")
);
$error = '';
foreach ($validate as $validation)
{
if (!preg_match($validation[1],$validation[0]))
{
$error .= $validation[2];
}
}
if($error != '')
{
echo $error;
exit;
}
Comment on this post,if it is not clear.
Thanks in advance!
If you want to check if at least required fields have been submitted, you can check whether they have been set and have a truthy value using the isset and empty functions.
For example:
if ( isset($_POST['username'], $_POST['password']) &&
! empty($_POST['username']) && ! empty($_POST['password']) ) {
// validation here
}
That would check if the username and password fields were submitted and have a value, whereas for example an email field wouldn't necessarily have been filled in for the above condition to return true.
If you know the mandatory fields before hand I'll suggest you group them in an array and test for based on the current key. If a key is in not mandatory but holds value you can test otherwise do your regular check.
$error = '';
$mandatoryFields = array('key1', 'key2' 'key3');
foreach ($validate as $validation)
{
if (!in_array($validation[0], $mandatoryFields) && strlen(trim($validation[0])) > 0)
{
// There is data in a non mandatory field.
// Perform your test.
}
else {
// Do your regular test.
if (!preg_match($validation[1],$validation[0]))
{
$error .= $validation[2];
}
}
}
You can give this a try.
I know this is embarrassing easy but I cannot get this to work right now, keep getting syntax errors, I just added in a jquery code that pre-fills in a form filed and when you select the form field it will clear the default value. The result though is if a user submits the form without changing the default value, I need to see if it exist in addition to my normal string sanitations
In this snippet below of PHP I need to run 2 conditions on $fname but below will not work, can someone help please
$fname = 'first name';
if (trim($fname) == '') && ($fname != 'first name') {
$err .= "error";
}else{
$err .= "all good";
}
For karim79
this code below from your example, exactly like this gives me this error
Fatal Error: Can't use function return value in write context on line 5
<?PHP
$fname = '';
if(empty(trim($fname))) {
echo "First name is empty";
}
?>
$fname = 'first name';
if (trim($fname) == '' || $fname != 'first name') {
$err .= "error";
} else {
$err .= "all good";
}
I would prefer to use strcmp:
if (trim($fname) == '' || strcmp($fname,'first name') !== 0) {
$err .= "error";
} else {
$err .= "all good";
}
If the case of the first name is not important, you should consider using strcasecmp instead. Also note you can use empty to test for the empty string:
$fname = '';
$fname = trim($fname);
if(empty($fname)) {
echo "First name is empty";
} else {
echo "Not empty";
}
When using empty, beware the following (from the manual):
Note: empty() only checks variables as
anything else will result in a parse
error. In other words, the following
will not work: empty(trim($name)).
$fname = 'first name';
if (trim($fname) == '' || $fname == 'first name') {
$err .= "error";
}else{
$err .= "all good";
}
PS: I assumed you want to raise an error if the string is either empty or the standard value. If that's wrong let me know.
I would NOT recommend using empty() for anything. It has some tricky return patterns, including telling you that a 0 is empty, and things of that nature. This, unfortunately, is a shortcoming of PHP.
Instead, try this algorithm (The following assumes your form POSTs):
<?php
$err = array();
// this is for sticklers..with E_STRICT on, PHP
// complains about uninitialized indexes
if( isset($_POST['name']) )
{
$name = trim($_POST['name']);
}
else
{
$name = '';
}
if( strlen($name) == 0 )
{
$err[] = "First name is required.";
}
// after validation is complete....
if( count($err) > 0 )
{
echo "There are errors!";
// probably something more elaborate here, like
// outputting an ordered list to display each error
print_r($err);
}
else
{
echo "It's all good!";
}
?>