Page 1 of 1

Not sure what is wrong with these IF statements

Posted: Sat Mar 08, 2014 10:46 pm
by chicago123
I'm a PHP beginner - I'm not sure what is wrong with this code. When $qotw is equal to 1, the 'cash' is increasing as its supposed to. However, when $qotw is equal to 2, the 'cash' value is still increasing and the message that should be displayed according to the 2nd IF statement is not showing up. The 'cash' value should only increase when $qotw is equal to 1.

I tried putting if($qotw == '1') instead of if(qotw = '1') but in that case only the second statement is executed and not the first (the message is displayed but the 'cash' and 'qotw' does not increase.

Please help me fix this so that BOTH statements will execute at the appropriate times. Thanks!

Code: Select all

<?php
$con=mysqli_connect("localhost","users","password","users");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

if($qotw = '1')
{
mysqli_query($con,"UPDATE users SET cash = cash + $scash
WHERE username = '". $_SESSION['username'] . "'");
mysqli_query($con,"UPDATE users SET qotw = 1 + qotw
WHERE username = '". $_SESSION['username'] . "'");
}

if($qotw = '2')
{
echo "You have already attempted this question.";
}

mysqli_close($con);
?>

Re: Not sure what is wrong with these IF statements

Posted: Sat Mar 08, 2014 10:59 pm
by requinix
You do need ==. One equals sign means assignment, two means comparison.

You do realize that the two sets of code cannot possibly execute at the same time, right? $qotw cannot be both "1" and "2" at the same time.

Re: Not sure what is wrong with these IF statements

Posted: Sat Mar 08, 2014 11:10 pm
by chicago123
Thank you for your reply.
Yes, I know they can't execute at the same time.
But now after I changed both of them to if($qotw == '1') and if($qotw == '2') neither of them execute when $qotw is equal to 1 or 2.

Thanks

Re: Not sure what is wrong with these IF statements

Posted: Sun Mar 09, 2014 12:37 am
by tiger0
If you have changed it to if($qotw == '1'), then the problem should be with your database or its connection.

Re: Not sure what is wrong with these IF statements

Posted: Sun Mar 09, 2014 3:08 am
by requinix
Where is $qotw being defined? Note that if you think it'll happen automatically because it's present in the URL or a form, that's not quite true.

Re: Not sure what is wrong with these IF statements

Posted: Sun Mar 09, 2014 1:03 pm
by chicago123
Thanks for your replies.

The problem was that I had define $qotw further down the page AFTER these statements. I realized that I had to define it BEFORE these statements and now it is working fine.

Thanks!