Check if both strings are empty not working - php

I have a conditional if check on a webform on which ajax (and php) is doing the submit work.
if(empty($name) or empty($message))
{
do something
}
The above is working if one of the 2 strings is empty.I want to add to the above
or (empty($name) and empty($message))
for checking if both strings are empty but in someway its not working!I want to make sure all 3 senarios are covered,Name empty or Message empty or both empty.
Any ideas?

This will check that both $name and $message is not blank, than true
if($name != '' && $message != '') {
//Do something
}
If you use this, this will check if any 1 field is empty than the condition is true
if($name == '' || $message == '') {
//Do something
}
If you use this, this will be true if both are empty
if($name == '' && $message == '') {
//Do something
}

Replace "or" with "||". Example:
if (empty($name) || empty($message))
{
// Do something
}

or means "If either condition is true", not "If exactly one condition is true".
The code you have already covers your requirement.

Related

Setting multiple if conditions in php

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) {

How do I check required fields using 'empty' in a field whose value is an integer?

I'm trying to run a check of my required fields where i use the empty function. Unfortunately empty considers 0 to be empty and my values could be 0 and one in the radio button. I've tried to use !is_int(myvalue) and yet it didn't work.
Here is my code:
<?php $required_fields = array('menu_name', 'position', 'visible');
foreach($required_fields as $fieldname) {
if(!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && !is_int($_POST[$fieldname]))) {
$errors[] = $fieldname;
}
}
?>
It appears you want to test a string to see if it is an integer.
Try using is_numeric
http://www.php.net/manual/en/function.is-numeric.php
if(!isset($_POST[$fieldname]) // not in the post
|| (empty($_POST[$fieldname]) && 0 != $_POST[$fieldname]) // empty but not zero
|| (int) $_POST[$fieldname] == '')) // not an integer
) {
$errors[] = $fieldname;
}

IF statements with OR operator not working

if($action == "send"){
$_POST['name'] = $name ;
$_POST['email'] = $email ;
$_POST['phone'] = $phone ;
if(!empty($name) || !empty($email) || !empty($phone)){
.....
} else {
$msg = 'All fields required';
}
//whatever I do only shows $msg.
//already tried that too
if(!empty($_POST['name']) || !empty($_POST['email']) || !empty($_POST['phone'])){
....
}
What Im trying to do is a form that email me the data, and I want all fields to be filled so maybe Im writing the if statement the wrong way.
sorry if I didnt explained well before.
Your code reads:
If name is not empty, or email is not empty, or phone is not empty
This means that as long as at least one of them are non-empty, then you're good!
Pretty sure that's not what you meant. You want:
If name is not empty, AND email is not empty, AND phone is not empty
Use && instead of || and it should just work!
I think you're getting confused by all the negatives involved here. I suspect what you're after is:
if (!(empty($name) || empty($email) || empty($phone))) {
...
} else {
$msg = 'All fields required';
}
Which would be better written (in my opinion) as:
if (empty($name) || empty($email) || empty($phone)) {
$msg = 'All fields required';
} else {
...
}
if($name=='' || $email=='' || $phone=='')
{
$msg='All fields required';
}
else
{
..............
}

Dynamic if-statement with variables?

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.

Small issue with IF.. OR statement on PHP

I'm trying to Validate email twice on a registration form, in order to do it i'm trying to first check that the actual email field isn't empty by running the "empty" function or both of the fields - but for some reason it wont accept it, it complains about unexpected '('
here's the line:
if (empty(($_POST['e-mail']) OR ($_POST['e-mail2']))) {
$error[] = 'Please Enter your Email ';
}
anyone has an idea why i'm getting it and how to fix it ?
Try:
if (empty($_POST['e-mail']) || empty($_POST['e-mail2'])) {
$error[] = 'Please Enter your Email ';
}
You might also want to include the isset() function to make sure the POST key is actually set before checking for a value.
Edit
Just for clarity, I'll post an edit here. If you want to validate both the existence of a value, and whether one value for an input equals another, you need to do two sanity checks:
// Check existence of values
if (empty($_POST['e-mail']) || empty($_POST['e-mail2'])) {
$error[] = 'Please Enter your Email ';
}
// Check equivalence
if ($_POST['e-mail'] != $_POST['e-mail2']) {
$error[] = 'Your e-mails do not match';
}
You're passing logical expression to empty(), which is obviously wrong
you need to check both variables separately
if (empty($_POST['e-mail']) OR empty($_POST['e-mail2'])) {
$error[] = 'Please Enter your Email ';
}
You meant:
if (empty($_POST['e-mail']) OR empty($_POST['e-mail2']))
PHP cannot guess that, it just evaluates your expression like that:
if (empty(($_POST['e-mail']) OR ($_POST['e-mail2'])))
if (empty('value_of_email1' OR 'value_of_email1' ))
if (empty( true ))
if ( false )
if one of the submitted values is truthish (i.e. not-empty), the OR expression still evaluates to true.
I don't think you can use logical expression within an empty() method.
Try separating logical expression to two separate empty() method calls.
Try:
if (empty($_POST['e-mail']) OR empty($_POST['e-mail2'])) {
$error[] = 'Please Enter your Email ';
}
For more information on empty(), take a look at PHP manual on empty().
For posterity...
$email1 = filter_var('aaa#email.com', FILTER_VALIDATE_EMAIL);
$email2 = filter_var('aaa#email.com', FILTER_VALIDATE_EMAIL);
$unmatched1 = filter_var('aaa#emil.com', FILTER_VALIDATE_EMAIL);
$unmatched2 = filter_var('aab#email.com', FILTER_VALIDATE_EMAIL);
$invalid1 = filter_var('aaa.com', FILTER_VALIDATE_EMAIL);
$invalid2 = filter_var('email.com', FILTER_VALIDATE_EMAIL);
$empty = filter_var('', FILTER_VALIDATE_EMAIL);
var_dump(!$email1 || $email1 !== $email2);
var_dump(!$email1 || $email1 !== $unmatched2);
var_dump(!$unmatched1 || $unmatched1 !== $email2);
var_dump(!$email1 || $email1 !== $invalid2);
var_dump(!$invalid1 || $invalid1 !== $email2);
var_dump(!$email1 || $email1 !== $empty);
var_dump(!$empty || $empty !== $email2);
Gives:
bool(false) // Desired in validation...
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
https://ignite.io/code/511f8bf8ec221e7f21000000
So if you replace var_dump with if and simplify e-mail2 (no need to validate):
$email = filter_var($_POST['e-mail'], FILTER_VALIDATE_EMAIL);
if (!$email || $email !== $_POST['e-mail2']) {
// error stuff, including separate check on empty.
}

Categories