Page 1 of 1

Tricky if statements...

Posted: Tue Mar 06, 2007 3:06 pm
by Mightywayne
Allo poppet. I gots me here a question about if statements. First here's the traditional code...

Code: Select all

if ($foodamount1 == 1 && empty($foodamount2) && empty($foodamount3) && $barn == 'cardboard' && $money >= 500 && $currentfood == 0)
	  {
	  mysql_query("UPDATE user SET food = food+500 WHERE username = '$user'");
	  mysql_query("UPDATE user SET money = money-500 WHERE username = '$user'");
	  die("<b>500</b> units of food bought sucessfully.");
	  }
	  else
	  echo "Hmm, it appears you do not have enough money for the food, or your barn is full. ";
	  
	  
	  
	  	  if ($foodamount1 == 1 && empty($foodamount2) && empty($foodamount3) && $barn == 'plywood' && $money >= 500 &&$currentfood >= 0 && $currentfood != 1000)
	  {
	  mysql_query("UPDATE user SET food = food+500 WHERE username = '$user'");
	  mysql_query("UPDATE user SET money = money-500 WHERE username = '$user'");
	  echo "<b>500</b> units of food bought sucessfully.";
	  }
	  else
	  echo "Hmm, it appears you do not have enough money for the food, or your barn is full. ";
The code itself works fine, but the problem is, I've got like tons of these on the page. So what ends up happening is that if the first one goes off, it'll say "Hmm, it appears blah blah" AND it'll say "500 units bought correctly" (assuming the instance is the second, and not the first). Basically, I need to know how to stop that. I was thinking I'd just take away the "else" part, but then there'd be no error message at all.

What's a good way to avoid this?

Posted: Tue Mar 06, 2007 3:22 pm
by feyd
here's a hint:

Code: Select all

if()
{}
elseif()
{}
else
{}

Posted: Tue Mar 06, 2007 3:24 pm
by Mightywayne
It's always those basic things that getcha. Damn. Totally forgot that even existed.

So, okay, then... are you saying I should smush all my if statements into one giant one?

Posted: Tue Mar 06, 2007 3:28 pm
by feyd
Unless you can come up with a more elegant way of performing the actions.

Honestly, it looks like you could write a function to perform the meat of it, then simply create some way of catching all the cases in a single if.

One thing you can fix right now is your two update queries. They can be combined.

Code: Select all

UPDATE user SET food = food+500, money = money-500 WHERE username = '$user'

Posted: Tue Mar 06, 2007 4:04 pm
by Mightywayne
Oh, superb! That's great, cuz food buying is a big part of the game. Okay thanks. <3 :D