PHP - Only run a search if a dropdown value is chosen - php

I have a search on a site which I only want to display any results if something has been entered into one of the fields. I'm not really a php person so the best I could do was by adding this before the search:
<?php code on how to get the listings ...
if ($search_location != "" || $search_keywords != "" ) {
... code on how to display the listings.} ?>
As far as I understand this will only display the results if either the location or keywords are not empty. Works well so far.
My problem: there is also a dropdown to select a category ... I tried adding this like:
if ($search_location != "" || $search_keywords != "" || $search_categories != "" ) {
But the search doesn't work if you only choose a category you have to enter in one of the other fields also, so I am assuming this was wrong.

I think you need AND (which is && in php):
if (($search_location != "" || $search_keywords != "") && $search_categories != "" ) {
// ^ here
Which means:
provide (search_location or search_keywords) and search_categories

Just posting the answer I got incase any one else needs it.
I had to use !empty like -
if ($search_location != "" || $search_keywords != "" || !empty($search_categories) ) {
I don't know why !empty works and != "" doesn't, still learning.
Thanks.
Liz.

Related

The Below IF condition is not working properly

I have an if statement which is the below one. But its not working i dont know the reason.
if ((($posted['pref_sal_brn'] != null || $posted['pref_sal_end'] != null) && $posted['pref_sal_prd'] != -1) || $posted['pref_sal_optn'] != -1){
// Success code
} else {
// Else Part
}
What's wrong in my code?
Here I need either one in first two, and if either one is not empty than the third one should be compulsory.
if these three should be true or the fourth one is true like this.
EDIT :
array(4) { ["pref_sal_brn"]=> string(3) "234" ["pref_sal_end"]=> string(3) "500" ["pref_sal_prd"]=> string(2) "47" ["pref_sal_optn"]=> string(2) "51" }
this is the output, first two parameters are salary begin and end, thrid one is period option like day, month, weekly,
and the fourth one is some options like , negotiable, minimum wage, like that. so first two are integers, third fourth are drop down lists for the items.
Just tested your code in phpfiddle.org and it is working properly. it will print success as it is supposed to
`
$posted['pref_sal_brn'] = "234";
$posted['pref_sal_prd'] = "47";
$posted['pref_sal_end'] = "500";
$posted['pref_sal_optn'] = "51";
if (( ($posted['pref_sal_brn'] != null || $posted['pref_sal_end'] != null) && $posted['pref_sal_prd'] != -1) || $posted['pref_sal_optn'] != -1) {
echo 'success';
} else {
echo 'failure';
}
?>
This answer is based on what i understand while reading and analyzing your question, Your question is kinda hard to understand but this is what i grasp so far. Correct me if im wrong
Based on my understanding you cannot have it with one liner condition. you might want to break them into separate ifs
You said:
I need either one in first two(pref_sal_brn and pref_sal_end), and if either one is not empty
then the third one should be compulsory. (do this if above is true)
if these three should be true (I understand this that 1 and 2 above should be true)
or the fourth one is true like this. (or if the fourth one is true then whole process is true)
Breaking them and turning them into code:
// CHECK FIRST IF THE pref_sal_optn is TRUE, IF IT IS TRUE THEN DISREGARD OTHER CONDITION
if ($posted['pref_sal_optn'] != -1) {
// success
}
// NOW CHECK IF pref_sal_brn OR pref_sal_end IS NOT NULL
elseif ($posted['pref_sal_brn'] != null || $posted['pref_sal_end'] != null) {
// YOU DISCOVERED THAT EITHER ONE OF pref_sal_brn OR pref_sal_end IS NOT NULL THEN CHECK IF pref_sal_prd IS != -1 IF TRUE THEN DO SUCCESS AGAIN
if ($posted['pref_sal_prd'] != -1) {
// success
} else {
// error
}
} else {
// error
}

If statement with && and multiple OR conditions in PHP

I'm having trouble trying to make the statement below work the way I want it to.
I am trying to display an error message for an order form if at least one text field is not filled out. Below is a snippet of my PHP code. The 'cookieGiftBox' is the name of a checkbox that users can select and if it is selected, they must enter an amount of cookies under their desired flavors in the text fields provided. How can I display an error message to display when the checkbox IS selected but NO text fields have been filled out?
<?php
if (isset($_POST['cookieGiftBox'])
&& (!isset($_POST['sugar'])
|| ($_POST['chocolateChip'])
|| ($_POST['chocolateChipPecan'])
|| ($_POST['whiteChocolateRaspberry'])
|| ($_POST['peanutChocolateChip'])
|| ($_POST['peanutButter'])
|| ($_POST['tripleChocolateChip'])
|| ($_POST['whiteChocolateChip'])
|| ($_POST['oatmealRaisin'])
|| ($_POST['cinnamonSpice'])
|| ($_POST['candyChocolateChip'])
|| ($_POST['butterscotchToffee'])
|| ($_POST['snickerdoodle']))) {
$error.="<br />Please enter an Amount for Cookie Flavors";
}
?>
&& takes precedence over ||, thus you would have to use parentheses to get the expected result:
if (isset($_POST['cookieGiftBox']) && (!isset($POST['sugar']) || ...)
Actually, to get check if nothing is selected, you would do something like this:
if checkbox is checked and not (sugar is checked or chocolatechip is checked) or the equivalent:
if checkbox is checked and sugar is not entered and chocolatechip is not entered....
If you want to know more, search for information about Boolean algebra.
Update: In your example and in the correct syntax the sentence I took as an example would like this (for the first sentence, note the not (!) and the parentheses around the fields, not the checkbox):
if (isset($_POST['cookieGiftBox']) &&
!(
isset($_POST['sugar']) ||
isset($_POST['chocolatechip'])
)
) { error ...}
Or the second sentence, which might be easier to understand (note the && instead of ||):
if (isset($_POST['cookieGiftBox']) &&
!isset($_POST['sugar']) &&
!isset($_POST['chocolatechip'])
) { error...}
Using ands makes sure it is only true (and thus showing the error) if none of the sugar, chocolatechips, etc. fields are set when the giftbox checkbox is checked.
So if the checkbox is checked, and no fields are set it looks like this:
(true && !false && !false) which is equivalent to (true && true && true) which is true, so it shows the error.
If the checkbox is checked and sugar is entered it would look like this:
(true && !true && !false), equ. to (true && false && true), equ. to false and thus no error is shown.
If both sugar and chocolatechip are entered also no error will be shown.
I have simillar issue:
I try use:
if (isset($this->context->controller->php_self) && ($this->context->controller->php_self != 'category') || ($this->context->controller->php_self != 'product') || ($this->context->controller->php_self != 'index')){ ... }
Thats didn't work, I change it to:
if (isset($this->context->controller->php_self) && ($this->context->controller->php_self != 'category') && ($this->context->controller->php_self != 'product') && ($this->context->controller->php_self != 'index')){ ... }
I dont know it is correct?
Edit. This is not correct, but for now i didnt know how to fix it.

IF OR condition isn't working as expected

I have a for loop, but I want to skip some of the loops if a condition is met.
This works fine, and will continue the loop if $option_nm isn't "Fonts".
if($option_nm != "Fonts"){
continue;
}
However, this doesn't work, and skips everything.
if($option_nm != "Fonts" || $option_nm != "Style" || $option_nm != "Thread" || $option_nm != "Textbox"){
continue;
}
I also tried changing || to Or which does the same thing.
What am I doing wrong?
You are confusing the OR statement.
Your code should be like:
if($option_nm != "Fonts" && $option_nm != "Style" && $option_nm != "Thread" && $option_nm != "Textbox"){
continue;
}
Your if condition always return true and loop goes continue, because your if condition you use or or ||.
try this one.
if($option_nm != "Fonts" && $option_nm != "Style" && $option_nm != "Thread" && $option_nm != "Textbox"){
continue;
}
Even though your post is over a year old, I'll give another solution.
You can utilize the in_array functionality in php and do an negative if statement around your statement.
$elements = array("Fonts", "Style", "Thread", "Textbox")
if (!in_array($option_nm, $elements)) { continue;}
This makes future maintenance simple and is easy to read.

Display HTML if two conditions are true or another two are true or third part of conditions are true

I have php if statement that should display certain HTML code if two conditions are true or another two are true or third part of conditions are true.
I have several arrays - $Options_arr, $MoreOptions_arr, $Special_arr .
To explain in the easiest possible way I want to do this:
if(!empty($Options_arr[0]) && $Options_arr[0]!="") or
(!empty($MoreOptions_arr[0]) && $MoreOptions_arr[0]!="") or
(!empty($Special_arr[0]) && $Special_arr[0]!="")
{?> some HTML here
All help will be appreciated thank you.
empty() already checks for empty string "" so it's shorter:
if(!empty($Options_arr[0]) || !empty($MoreOptions_arr[0]) || !empty($Special_arr[0])) {
//some HTML here
}
BragG, you can use elseif
Like:
if((!empty($Options_arr[0]) && $Options_arr[0]!="") ||
(!empty($MoreOptions_arr[0]) && $MoreOptions_arr[0]!="") ||
(!empty($Special_arr[0]) && $Special_arr[0]!=""))
{
// some html or any code
}
I hope that is what you were looking for..
Feel free to ask any question.
You are just missing some brackets. Also || is more frequently used than OR
if((!empty($Options_arr[0]) && $Options_arr[0]!="") || (!empty($MoreOptions_arr[0]) && $MoreOptions_arr[0]!="") || (!empty($Special_arr[0]) && $Special_arr[0]!="")){
echo '<p>hello</p>';
}
You're basically already there...
if (
(!empty($Options_arr[0]) && $Options_arr[0]!="")
|| (!empty($MoreOptions_arr[0]) && $MoreOptions_arr[0]!="")
|| (!empty($Special_arr[0]) && $Special_arr[0]!="")
){
...do something
Basically you write an if statement that resolves if any of the sub-statements are true by joining the sub-statements together with ORs

PHP if/else and AND/OR to check mandatory and optional fields

I have eight input fields in my form that I need to check whether they are empty. Four of these are text fields, the other four are list boxes. When the user submits the form, the four text boxes need to be filled. The fifth field is a Yes/No selection. If the selection in this field is "No", then the remaining three can be left blank. However, if the selection in the fifth field is "Yes" then the last three also have to be selected using the list boxes.
Let us call the first four (textboxes) "mandatory-text1", "mandatory-text2", "mandatory-text3", and "mandatory-text4", the Yes/No selection list box "yes-no" and the optional selections "a", "b" and "c".
SO:
If mandatory-text1, or mandatory-text2, or mandatory-text3, or mandatory-text4, are blank, the processing php will abort.
However, if mandatory-text1, mandatory-text2, mandatory-text3, and mandatory-text4, are all filled in, the next check is to see whether the yes-no contains a "Yes" or a "No".
If it contains a No, then a, b and c have to be necessarily left
blank.
If it contains a Yes, then a, b and c (list boxes) have to be
necessarily selected.
With my level of proficiency in PHP, I have been able to reach this far:
if ((mandatory-text1 || mandatory-text2 || mandatory-text3 == "") OR (yes-no == "Yes" AND (!(a || b || c == ""))) {
echo "blah" ;
exit();
}
else {
//do some stuff
}
I haven't coded the 'do some stuff' part yet because when I try this code, I get the 'blah' message even when all the text fields are filled in, the yes-no is "Yes" and a, b and c have been selected.
I tried it first with a simple "||" for all the fields and that works fine - i.e. if even one of the fields is left blank I get the 'blah' message. I have also tried just checking for the yes-no and a,b,c and that too works fine i.e. if there is a Yes in the yes-no i get the blah if the a,b,c fields are blank.
But I need to satisfy all the conditions before I can proceed to the next step. The posts I have read here on SO brought me to the stage I am in right now. But none went to the level I want for my project.
Any hints for the logic would be appreciated!
Okay first of all, you are supposed to use $ before variable names
Second,
mandatory-text1||mandatory-text2||mandatory-text3==""
is wrong logic. It should be $mandatory-text1=""||$mandatory-text2==""|| ...
It works because if(mandatory-text1) alone means if mandatory-text1 is defined and not empty or null string, so in this case $mandatory-text1||$mandatory-text2||$mandatory-text3 alone is sufficient
if ((mandatory-text1 || mandatory-text2 || mandatory-text3 == "") OR (yes-no == "Yes" AND (!(a || b || c == ""))) {
echo "blah" ;
exit();
}
else {
//do some stuff
}
same for a||b||c
(mandatory-text1 || mandatory-text2 || mandatory-text3 == "")
This isn't working the way you think it is. This says:
if mandatory text 1 is not empty or mandatory 2 text is not empty or mandatory 3 text is equal to ''.
Try:
(mandatory-text1 == "" || mandatory-text2 == "" || mandatory-text3 == "")
You may redesign your control in a more readable way, with a function or code block per field type, for example :
<?php
function checkFields( $data )
{
// List of field to check
$fields = array( 'mandatory-text1', 'mandatory-text2', 'mandatory-text3', 'mandatory-text4', 'a', 'b', 'c' );
foreach ($fields as $field )
{
switch( $field )
{
case 'mandatory-text1':
case 'mandatory-text2':
case 'mandatory-text3':
case 'mandatory-text4':
if ( $data[$field] == '' )
{
return false;
}
break;
case 'a':
case 'b':
case 'c':
if ( $data['yes-no'] == 'yes' && $data[$field] == '' )
{
return false;
}
elseif( $data['yes-no'] == 'no' && $data[$field] != '' )
{
return false;
}
break;
}
}
// If we have not returned false so far, then all is clear
return true;
}
// Usage :
if( checkFields( $_POST ) )
{
// every thing is ok
}
else
{
// bad submission
}
?>
You should mostly avoid 2 things here :
Long AND / OR statements
Repeating your self with the smae controls
If I understood correctly, something like this should work. Do NOT use dashes in variable names.
if ($mandatory1 && $mandatory2 && $mandatory3 && $mandatory4)
{
if ($choice == "Y" && $a && $b && $c)
{
// do whatever
}
elseif ($choice == "N" && !$a && !$b && !$c)
{
// do something else
}
}
else
{
// submission incorrect
}

Categories