Using if and else statements error - php

I have created two links where I would like the page contents to change. The problem is the URL changes but not the page content.
<h3>Filter Results</h3>
<p><a href="index.php?filter='Action'>Action</a></p>
<p>Comedy</p>
if (isset($_GET['filter']) == 'Action') {
echo 'Action';
}
else if (isset($_GET['filter']) =='Comedy') {
echo 'Comedy';
}
It always outputs the first link information "Action".

Your links are faulty:
<p>Action</p>
<p>Comedy</p>
<!-- ^ ^ No single quotes (' ') -->
Yogesh Suthar pointed it out first
Also, isset() will return a boolean (true or false; based on whether or not the variable is set). You're comparing a boolean to a string, a string will always be converted into TRUE (unless the string is "false" or similar), so basically, if the variable is set, the first condition will always match.
You want
if (isset($_GET["filter"]) && $_GET["filter"] === "Action")
Note the use of ===, this will make sure that the variable is exactly what you think it is, and not some sort of other type variable.
Few more points (Shamelessly stolen taken from other answers)
If there are multiple possible filters, check for the variable existance once, and use a switch/case block to determine which of them it is:
if(isset($_GET['filter'])) {
switch($_GET['filter']) {
case 'Action':
echo 'Action';
break;
case 'Comedy':
echo 'Comedy';
break;
}
}

The function isset will only check if the variable is existing! It will not return its value! Try this instead:
<h3>Filter Results</h3>
<p>Action</p>
<p>Comedy</p>
if(isset($_GET['filter']) && $_GET['filter'] == 'Action'){
echo 'Action';
}
else if(isset($_GET['filter']) && $_GET['filter'] == 'Comedy') {
echo 'Comedy';
}
Also, using switch might make things easier in the future:
<h3>Filter Results</h3>
<p>Action</p>
<p>Comedy</p>
if(isset($_GET['filter'])) {
switch($_GET['filter']) {
case 'Action':
echo 'Action';
break;
case 'Comedy':
echo 'Comedy';
break;
}
}

As #MadaraUchiha said about isset and,
if(isset($_GET['filter']) == 'Action')
should be
if(isset($_GET['filter']) && $_GET['filter'] == 'Action')
Also
<a href="index.php?filter='Action'>Action</a>
^ ^ ^ // here you started " but not ended and remove the single quotes around Action
should be
Action

Make sure that you insert an opening and a closing php tag: <?php and ?> To simplify it a bit you could just echo the value you get via $_GET
<h3>Filter Results</h3>
<p><a href="index.php?filter='Action'>Action</a></p>
<p><a href="index.php?filter='Comedy'>Comedy</a></p>
<?php
if(isset($_GET['filter'])){
echo $_GET['filter'];
}
?>

The function isset will return true or false (it checks whether the variable is set or not). Change your code:
if(isset($_GET['filter']) && $_GET['filter'] == 'Action') {

Your if condition is not correct do it:
if(isset($_GET['filter']) && $_GET['filter'] == 'Action'){
echo 'Action';
}
Similarly with else if:
else if(isset($_GET['filter']) && $_GET['filter'] =='Comedy') {
As you are comparing the isset($_GET['filter']) with the value although isset returns true of false so you need to compare the value of $_GET['filter'].

you dont have to use isset() and then compare.
$filter = $_GET['filter'];
if(isset($filter)){
if($filter == 'Action'){
echo 'Action';
}else if($filter == 'Comedy'){
echo 'Comedy';
}
}

isset returns true and since 'Action' is not null, it evaluates to true.
if ((isset($_GET['filter'])) && ($_GET['filter'] == 'Action')) {
// ...
} else if ((isset($_GET['filter'])) && ($_GET['filter'] == 'Comedy')) {
// ...
}
BTW such code would sooner or later become a nightmare to maintain.
You could instead, for example
function preventDirectoryTraversal($requestParam) {
return preg_replace("/\//", "", $requestParam);
}
// ...
if (isset($_GET['filter'])) {
$filterName = preventDirectoryTraversal($_GET['filter']);
include(FILTERS_DIR . "/" . $filterName . ".php");
}
or something alike. Of course this can be further improved, but I hope you get the point.

Wrong use of isset, check documentation, return a boolean.
if (isset($_GET['filter']))
{
switch ($_GET['filter'])
{
case 'Action':
//TODO
break;
case 'Comedy':
// TODO
break;
default:
// TODO
break;
}
}

//isset will always return true or false
if(isset($_GET['filter'])){
if($_GET['filter']=='Action')
{
echo 'Action';
}elseif($_GET['filter']=='Comedy'){
echo 'Comedy';
}
}

Related

How to generate dynamic IF statement

I have array look like this.
$setLogic = array(array("Conj"=>null,"Topic"=>True),array("Conj"=>"Or","Topic"=>True),array("Conj"=>"Or","Topic"=>false),
I try to build a IF statement with the dynamicly with this way.
foreach($setLogic as $value){
echo $value['Conj'].(int)$value['Topic'];
if($value['Conj'].(int)$value['Topic'] == true){
$getBoolean[] = true;
}
else{
$getBoolean[] = false;
}
I just need something like this.
(true or true or false) and return true or false
I found my answer with my self.
It's look like this.
$abc= '';
foreach($setLogic2 as $key => $value){
$abc.= $value['Conj'].' '.(int)$value['Topic'].' ';
}
//$abc = "0 And 1 And 1";
if(eval("return $abc;") == true) {
echo 'true boolean';
}
else if(eval("return $abc;") == false){
echo 'false boolean';
}
else{
echo 'none';
}
Ok i will re formulate my answer....
You want to dynamically evaluate an array which contains for each subarray
* a verb : "and" or "or"
* a value "true or "false"
Quicker and most dirty way is to use eval().
* build your conditions as a string (replace "and" by "&&" and "or" by "||"
'true || true && false'
then put the result in a variable and evaluate
eval('$result = (true || true && false);');
var_dump($result);
This works for sure...

How to check in PHP if variable is set and check if two values match set variable?

I know that is basic question, but i can't figure out how to test if $_GET['zanr'] contains '' or 'sve' to do other stuff in my script...i try using this code but it only checks '' and 'sve' is ignored...so how to check if 'zanr' contains '' or 'sve' do stuff a else do stuff b?
if (isset($_GET['zanr']) === '' || isset($_GET['zanr']) === 'sve'){
echo "zanr = '' or 'sve'";
} else {
echo "zanr contains other values...";
}
I also try using ?? but no success...thanks.
Since your goal is to check if your $_GET is empty, use PHP built in function: empty(). And your second statement is wrong because isset() is returning a boolean and therefore you're not validating the string itself. So be sure to remove isset() and just compare if $_GET['zanr'] has your specific string.
Use this:
if (empty($_GET['zanr']) || $_GET['zanr'] == 'sve'){
echo "zanr = '' or 'sve'";
} else {
echo "zanr contains other values...";
}
Try below code.
if (isset($_GET['zanr']) && ($_GET['zanr'] == '' || $_GET['zanr'] == 'sve')){
echo "zanr = '' or 'sve'";
} else {
echo "zanr contains other values...";
}

if statement with $_GET disappears after run

When Edit comment is pressed it sends ?edit=true to the same page. It then runs the second if statement chaning the >Edit comment< into >Save comment<. But when pressed >Save comment< it wont change back to >Edit comment<..
How can I make it change back into >edit comment< ?
The same goes for the contenteditable attribute being set to true or false. It only changes to true but won't change back to false.
Also I had no idea what to set as title so feel free to edit it lol.
kritiek.php
function is_logged_in(){
if($_SESSION["admin_logged_in"]){
return true;
} else {
return false;
}
<?php if (is_logged_in()) {
if ($_GET['edit'] === 'edit_false' || $_GET['edit'] == "") {
echo "<a href='kritiek.php?edit=edit_true'>Edit comment</a>";
}
if ($_GET['edit'] === 'edit_true') {
echo "<a href='kritiek.php?edit=edit_false'>Save comment</a>";
}
} ?>
<p <?php if($_GET['edit'] === 'edit_true'){ edit_comment(true);}
if($_GET['edit'] === 'edit_false'){ edit_comment(false); }?>
><?php echo $row['comments']; ?></p>
function edit_comment($link) {
if (is_logged_in()) {
if($link === true) {
echo "contenteditable='true'";
} else {
echo "contenteditable='false'";
}
}
}
?>
EDIT: changed
$_GET['edit'] == true
to
$_GET['edit'] === 'edit_true'
disappearing the button completely.
EDIT: fixed that by changing
if ($_GET['edit'] === 'edit_false'
to
if ($_GET['edit'] === 'edit_false' || $_GET['edit'] == "")
you're checking for a Boolean false not the string 'false' so ..
if ($_GET['edit'] == false) {
to
if ($_GET['edit'] === 'false') {
obviously change the other checks also
The better way to compare user input from the outside is to use filter_input, since all input is ultimately parsed as a string in PHP. You can't compare boolean values like that directly to a string (i.e. 'false' != false).
Instead, you could try something like this...
if (filter_input(INPUT_GET, 'edit', FILTER_VALIDATE_BOOLEAN) == false) {
/* $_GET['edit'] is false */
} elseif (filter_input(INPUT_GET, 'edit', FILTER_VALIDATE_BOOLEAN) == true) {
/* $_GET['edit'] is true */
}
This makes the comparison safer, since filter_input() will parse a string of "1", "true", "on", and "yes" as a boolean true and will parse a string of "0", "false", "off", "no", and "" - an empty string - as a boolean false. Additionally, if $_GET['edit'] is not set or null, filter_input() will still return null, still making it falsey, which is still much more expected and obvious behavior than trying to compare strings to booleans.
My prefered way of doing it is using the id of the item being edited. The lack of the edit key being false than it's a simple
isset( $_GET['edit'] )
style check that avoids all that type based stuff. And what are you editing, why this id
url?edit=1
Edit id #1 or what have you.

php and $_GET array

I have submitted some code to the redirected url and now trying to use this to echo some information out but can't figure out where I am going wrong.
I have the following code:
<?php $login_attempt = mysql_real_escape_string($_GET['login_attempt']);
if ($login_attempt) == '1'{
return 'failed';
}
?>
all I want to do is if the url has $login_attempt=1 I want to return the message 'failed' to the page.
There is no point of escaping anything if it doesn't enter anywhere important (like a database).
<?php
if ($_GET['login_attempt'] == '1') {
echo 'failed';
}
?>
Also, you have a problem in your if statement, that's corrected in the code above. Be sure to include all of the condition inside of parenthesis, and not just one side of the equality check.
Also, if you wish to display something on the screen, you should echo it, not return.
how about:
if ($login_attempt == '1'){
echo 'failed';
}
Try this one. Your error in $login_attempt == '1':
<?php $login_attempt = mysql_real_escape_string($_GET['login_attempt']);
if ($login_attempt == '1'){
echo 'failed';
return false;
}
?>
As others already mentioned you have several problems but the syntax error comes from this:
if ($login_attempt) == '1'{
it should be
if ($login_attempt == '1') {
Dont u think if ($login_attempt) == '1' should be something like this ($login_attempt == '1') Sorry...many others also suggested this :P
At the first, I must tell you that you have a mistake in your IF condition. You typed == outside of ().
In addition, you have to be aware of status of setting your variable through your URL. Check the code below. In this code, I made a function to check the status. Default status is true, and we will check it just for a negative condition. I hope it could be useful for you:
<?php
function check() {
if (isset($_GET['login_attempt'])) {
$login_attempt = mysql_real_escape_string($_GET['login_attempt']);
if ($login_attempt == '1') {
return false;
} else {
return true;
}
} else {
return true;
}
}
if (!check()) echo('Error Message');
?>

Problem with Boolean Values in PHP

I've some problems with handling Boolean values in PHP. It is a validation script before storing data into database. I wrote a global validator that will validate and return a Boolean value whether the validation was successful .
Here is my code.
//VALIDATE
$isValid = true;
foreach($team as $key=>$val) {
if(!is_array($val)){
$isValid = $isValid && validate($val, $key);
}
}
for($it=0;$it<count($team['members']);$it++){
foreach($team['members'][$it] as $key=>$val) {
$isValid = $isValid && validate($val, $key);
}
}
if(!$isValid) { // EDITED: if(!isValid)
echo "validation error";
exit(1);
}
//END OF VALIDATE
The validate function is working properly but sometimes I end up getting $isValid = true or the other way, when I try with some test cases.
Hmm.. What am I doing wrong here ?
Please check, if this form does the trick:
if( false === $isValid) {
echo "validation error";
exit(1);
}
Note, that ( ! $isValid ) or (false == $isValid ) in some cases return results, which are at first look wrong. See for example the hint in the strpos() documentation.
In fact, the results are fine, since operations line ! or == try to cast operands in a 'useful' way.
That said, it's always better to user the === operator, since it checks values and types of operands. Please see operator overview.
if(!isValid) { falls back to if (!"isValid"), if there is no constant isValid. You probably meant if (!$isValid) {.
if(!isValid) {
isValid has no dolar, (you need to give variables in PHP some cash) so:
if(!$isValid) {
Source : http://bit.ly/1hxDmVR
Here is sample code for working with logical operators in PHP. Hope it will helpful:
<html>
<head>
<title>Logical</title>
</head>
<body>
<?php
$a=10;
$b=20;
if($a>$b)
{
echo " A is Greater";
}
elseif($a<$b)
{
echo " A is lesser";
}
else
{
echo "A and B are equal";
}
?>
<?php
$c=30;
$d=40;
//if(($a<$c)AND($b<$d))
if(($a<$c)&&($b<$d))
{
echo "A and B are larger";
}
if(isset($d))
$d=100;
echo $d;
unset($d);
?>
<?php
$var1=2;
switch($var1)
{
case 1:echo "var1 is 1";
break;
case 2:echo "var1 is 2";
break;
case 3:echo "var1 is 3";
break;
default:echo "var1 is unknown";
}
?>
</body>
</html>
I think the problem is that your $isValid variable can be changed many times in the loops and by the end of your code simply applies to the last value in your final loop.
You should set it to true initially and then only set it to false IF your validity check fails - not simply assign its value based on every single validity check.

Categories