This question already has answers here:
PHP logical AND operator error [closed]
(5 answers)
Closed 9 years ago.
Complete PHP noob here with an error returning because of a big nested if block. The error varies as I change the code, but it is always to do with the if statement. What is the correct way to do this statement?
Here is the incorrect if block:
if(!empty($_GET['x2'])) and (!empty($_GET['x'])) and (!empty($_GET['num']))
{
$xsqrd = $_GET['x2'];
$x = $_GET['x'];
$num = $_GET['num'];
if(($xsqrd*2)==0.0)
{
print $errdivzero;
}
else if(sqrt(pow($x,2)-(4*$xsqrd*$num)))
{
print $errsqrtmin1;
}
else
{
$ans1 = (-$x)+(sqrt(pow($x,2)-(4*$xsqrd*$num)))/(2*$xsqrd);
$ans2 = (-$x)-(sqrt(pow($x,2)-(4*$xsqrd*$num)))/(2*$xsqrd);
}
}
if(!empty($_GET['x2']) && !empty($_GET['x']) && !empty($_GET['num']))
{
$xsqrd = $_GET['x2'];
$x = $_GET['x'];
$num = $_GET['num'];
if(($xsqrd*2)==0.0)
{
print $errdivzero;
}
else if(sqrt(pow($x,2)-(4*$xsqrd*$num)))
{
print $errsqrtmin1;
}
else
{
$ans1 = (-$x)+(sqrt(pow($x,2)-(4*$xsqrd*$num)))/(2*$xsqrd);
$ans2 = (-$x)-(sqrt(pow($x,2)-(4*$xsqrd*$num)))/(2*$xsqrd);
}
}
You have extra ( in if condition and also you declared and which is not php function. you need to replace and with &&.
Now it's working fine without any error message.
if(!empty($_GET['x2']) && (!empty($_GET['x']) && (!empty($_GET['num']))
// ^ extra bracket ^ extra bracket
{
$xsqrd = $_GET['x2'];
$x = $_GET['x'];
$num = $_GET['num'];
if(($xsqrd*2)==0.0)
{
print $errdivzero;
}
else if(sqrt(pow($x,2)-(4*$xsqrd*$num)))
{
print $errsqrtmin1;
}
else
{
$ans1 = (-$x)+(sqrt(pow($x,2)-(4*$xsqrd*$num)))/(2*$xsqrd);
$ans2 = (-$x)-(sqrt(pow($x,2)-(4*$xsqrd*$num)))/(2*$xsqrd);
}
}
You had extra closing brackets at the position highlighted above. Also replace and with &&
Well let's check your brackets:
if(!empty($_GET['x2'])) and (!empty($_GET['x'])) and (!empty($_GET['num']))
^ ^
The second highlighted bracket closes the if statement - this will cause an error, you should remove unnecessary brackets like so::
if(!empty($_GET['x2']) and !empty($_GET['x']) and !empty($_GET['num']))
In future you should carefully check that for each opening bracket the closing bracket is where you expect it to be, and don't go overboard with the number of brackets.
Related
I'm having an issue when I enable the code below that it is causing my code to crash. I can't figure out where its crashing but I know if I comment out this portion that it will allow the code to run, just not have the checks ran on the other portions of the form.
if (empty($_POST["SCreq"])) {{
$SCreqERR = "SC requires a Yes or No answer";
} else {
$SCreq = test_input($_POST["SCreq"]);}
// elseif($SCreq = "Yes"; $Email=False)
// $EmailERR = "Email is required for SC"
// elseif ($SCreq = "Yes"; $emaildist1 = "")
// $emaildist1ERR = "First Email Distrobution Group required with SC"
// else {
// $emaildist1 = test_input($_POST["emaildist1"])
}}
Any help would be greatly appreciated, I have everything name, and all is the correct case.
The double-quotes basically start a new block within your "if" block. So, your code could be written like this:
if (empty($_POST["SCreq"])) {
{
$SCreqERR = "SC requires a Yes or No answer";
}
else {
$SCreq = test_input($_POST["SCreq"]);
}
}}
Not only are the brackets unbalanced (there's more closing brackets than opening brackets), the "else" also starts inside the "if" block. Removing the {} inside the "if", you get
if (empty($_POST["SCreq"])) {
else {
$SCreq = test_input($_POST["SCreq"]);
}
}}
which isn't valid (the "else" has to come directly after the "if" block, not within it).
Use proper indenting to catch those mistakes quickly. After each "{", start a new line, and indent your code more. After each "}", start a new line, and indent less. After each block, you need to be at the same indent-level as you were before, otherwise you have extra "{"s or "}". You can either do that manually, or have a good editor that does it for you. This kind of code uses proper indenting, and would be valid:
if (empty($_POST["SCreq"])) {
$SCreqERR = "SC requires a Yes or No answer";
}
else {
$SCreq = test_input($_POST["SCreq"]);
}
Use an IDE to help check that things are nested correctly. Hard to tell with things commented out though but... {{. Also, error logs!
I assume you looked at the documentation? http://php.net/manual/en/control-structures.elseif.php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
elseif($SCreq == "Yes" && $Email == False)
$EmailERR = "Email is required for SC";
elseif ($SCreq == "Yes" && $emaildist1 == "")
$emaildist1ERR = "First Email Distrobution Group required with SC";
else {
$emaildist1 = test_input($_POST["emaildist1"]);}
Condition test is ==
multiple AND condition put &&.
End your statements with ;
This question already has answers here:
The 3 different equals
(5 answers)
Closed 7 years ago.
I'm trying to compare two strings (one from my database and another supplied by the user) and see if they match! The problem I'm having is that they don't seem to match - even though the strings seems to be exactly identical?
My PHP code is below:
public function Verify($pdo, $id, $token) {
$prepsql = $pdo->prepare("SELECT * FROM Profiles WHERE id = '$id' LIMIT 1");
$prepsql->execute();
$currentrow = $prepsql->fetch();
$current = preg_replace("/[^a-zA-Z0-9]+/", "", $currentrow["token"]);
echo '<p>'.var_dump($current).'</p>';
echo '<p>'.var_dump($token).'</p>';
$token = preg_replace("/[^a-zA-Z0-9]+/", "", $token);
if ($current == null || $current = "") {
return false;
} else {
if (strcmp($token, $current) == 0) {
return true;
} else {
return false;
}
}
}
And here is the webpage output:
string(244) "CAAW4HRuZBuB4BACA7GffOAwLHgmLgMMLGQxDAw8IJDCwahZAh0S4wZAcP8Q9DmMwsDpBq7jFcH1EzUIsZBbhKov12utoYFQns0HhgB5xKLeDqtZBRqavaNjNSn7KAcObZAEcavQCRbGlVKZBArfDEHskBSR8qAoU543DVTZCOyHm5oYNDVafwHl0bAkc4jyIhh2YHEPaNpWGC0FhezsSidOgLjnfFq8CeLVxHH0nUZBMLgAZDZD"
<p></p>string(244) "CAAW4HRuZBuB4BACA7GffOAwLHgmLgMMLGQxDAw8IJDCwahZAh0S4wZAcP8Q9DmMwsDpBq7jFcH1EzUIsZBbhKov12utoYFQns0HhgB5xKLeDqtZBRqavaNjNSn7KAcObZAEcavQCRbGlVKZBArfDEHskBSR8qAoU543DVTZCOyHm5oYNDVafwHl0bAkc4jyIhh2YHEPaNpWGC0FhezsSidOgLjnfFq8CeLVxHH0nUZBMLgAZDZD"
<p></p><p>Not authenticated</p>
Not authenticated just means that this function is returning false...
What on earth am I doing wrong? As per advice given on other similar Stack Overflow answers, I've used the regex function to basically only keep alphanumeric characters but that has made no difference? It isn't a trimming issue either as that didn't work!
Any help would be much appreciated!
Thanks!
Here is your problem:
if ($current == null || $current = "") {
// ^ now `$current` is "", an empty string
You assign a new value to $current, an empty string.
You probably want something like:
if ($current == null || $current == "") {
// ^^ now you are comparing
This question already has answers here:
The 3 different equals
(5 answers)
Closed 8 years ago.
<?php
if ($user->getProfile()->get('title')="Canon"); {
echo "Test1"; }
else {
echo "Test2"; }
?>
This is causing my site to break, is there an obvious mistake?
Thank you.
= is an assignment, you want == for a comparison.
You also shouldn't have a ; between ) and {.
This will work:
<?php
if ( ($user->getProfile()->get('title')) == "Canon" ){
echo "Test1";
}
else {
echo "Test2";
}
?>
First of all You need a comparison '==' and not an assigning '='
And then You have a syntax error with a ';' after the condition
You need to change the = sign to == as the first one assigns a values while the latter one compares it.
And also, you don't need to terminate the if statement with a semicolon
if ($user->getProfile()->get('title') == "Canon") /* note that there is no semicolon here */
{ echo "Test1"; }
else
{ echo "Test2"; }
<?php
if ($user->getProfile()->get('title')=="Canon") {
echo "Test1";
}
else {
echo "Test2";
}
?>
Try this.
I have two combo boxes, one to report scores and one to set who scored the goals, How can i make it so if on post['submit']
If $_POST['Score1'] and $_POST['Score2']
is other than equal to
$_POST['homegoalscorer1'] and $_POST['awaygoalscorer1']
then echo"fail";
Something like;
if(isset($_POST['submit']))
{
$homescore = $_POST['Score1'];
$awayscore = $_POST['Score2'];
$homegoalscorer = $_POST['homegoalscorer1'];
$awaygoalscorer = $_POST['awaygoalscorer1'];
if '$homescore' + '$awayscore' != $homegoalscorer + $awaygoalscorer {
echo "failed";
}
else {
}
}
Any ideas?
Single quotes on a variable will turn that variable intro a string without execution. Also you forgot to add brackets:
if(isset($_POST['submit'])) {
$homescore = (float)$_POST['Score1'];
$awayscore = (float)$_POST['Score2'];
$homegoalscorer = (float)$_POST['homegoalscorer1'];
$awaygoalscorer = (float)$_POST['awaygoalscorer1'];
if (($homescore+$awayscore) != ($homegoalscorer+$awaygoalscorer)) {
echo "failed";
} else {
}
}
Use some brackets in your if statement to force the conditional setting in the correct context - and why are you encapsulating your variables in single quotes?
if (($homescore + $awayscore) != ($homegoalscorer + $awaygoalscorer))
{
// Your code continues....
I keep getting an error with the following bit of code. It is probably some small thing but I don't see what is wrong.
while($row = mysql_fetch_array($result))
{
$varp = $row['ustk_retail'];
if ($varp<80000) { $o1 = 1; }
if (($varp=>80000) && ($varp<100000)) { $o2 = "1"; }
if (($varp=>100000) && ($varp<120000)) { $o3 = "1"; }
if (($varp=>120000) && ($varp<140000)) { $o4 = "1"; }
if (($varp=>140000) && ($varp<160000)) { $o5 = "1"; }
if (($varp=>160000) && ($varp<180000)) { $o6 = "1"; }
if (($varp=>180000) && ($varp<200000)) { $o7 = "1"; }
if (($varp=>200000) && ($varp<220000)) { $o8 = "1"; }
if (($varp=>220000) && ($varp<240000)) { $o9 = "1"; }
if (($varp=>240000) && ($varp<260000)) { $o10 = "1"; }
if (($varp=>260000) && ($varp<280000)) { $o11 = "1"; }
if (($varp=>280000) && ($varp<300000)) { $o12 = "1"; }
if ($varp>=300000) { $o13 = "1"; }
}
Running php -l (lint) on your code I get a
Parse error: syntax error, unexpected T_DOUBLE_ARROW
The T_DOUBLE_ARROW token is what PHP expects when assigning array values to array keys.
When comparing for Greater than or equal to the PHP Parser expects T_IS_GREATER_OR_EQUAL, meaning you have to use >= instead of =>.
See
the chapter on Comparison Operators in the PHP Manual and
the List of Parser Tokens in the PHP Manual
Greater than or equal to is >= sign, not =>
Update:
You are right. It's small but hard to find mistake.
It took me to split whole line into pieces to see where the problem is:
<?php
if
(
$varp
=>
80000
)
So, it says parse error on line 5 and I had to doublecheck this operator.
Of course, at first I separated the problem line from the rest of the code to be certain.
You have an expression error.
$varp=>220000 // is not a valid php expression
=> operator is used to assign values in arrays like:
$x = array( 'foo' => 'bar');
>= is the comparation assigment greater than or equal
You have made a mistake in the if conditions. The greater than Equal to sign is >= and not =>.
The answer has already been given but thought this was neat enough to share:
PHP accepts boolean expressions in it's switch statement.
switch(TRUE) {
case $range <= 10: echo "range below or equal to 10"; break;
case $range <= 20: echo "range above 10 below or equal to 20"; break;
case $range <= 30: echo "range above 20 below or equal to 30"; break;
default: echo "high range";
}
In my opinion this generates the cleanest most readable code.
This is more readable and compact way to do the same:
$ranges = range(300000, 80000, -20000);
$index = 1;
$varp = 220001;
foreach ($ranges as $i => $range) {
if ($varp >= $range) {
$index = 13 - $i;
break;
}
}
${'o' . $index} = 1;
Anyway - I think you're doing something wrong with using variable name of result.
You probably want to change ($varp=300000) to ($varp==300000) and it might help to enclose the full if-statement inside (), like this
if($varp80000 && $varp100000 && $varp120000 && $varp140000 && $varp160000 && $varp180000 && $varp200000 && $varp220000 && $varp240000 && $varp260000 && $varp280000 && $varp==300000) { $o13 = "1"; }
On another note, where to these strange $varp#### variables come from?
Not sure whether the code you've posted has gotten messed up somehow, but it looks like you're missing "==" in some of the if conditions. Also, as Skilldrick pointed out, the whole if condition should be in parentheses
"Greater than or equal to is >= NOT =>. You use => for arrays for keys/values.
Add one more bracket around the conditions in if....
if ( ($varp80000) && ($varp100000) && ($varp120000) && ($varp140000) && ($varp160000) && ($varp180000) && ($varp200000) && ($varp220000) && ($varp240000) && ($varp260000) && ($varp280000) && ($varp=300000) ) { $o13 = "1"; }