elseif not working correctly

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pinehead18
Forum Contributor
Posts: 329
Joined: Thu Jul 31, 2003 9:20 pm

elseif not working correctly

Post by pinehead18 »

Code: Select all

if(isset($sec)) { $sql = "SELECT * FROM posts WHERE id='$id' AND section='$sec' ORDER BY id DESC"; } 
	
elseif($sec == "showall") {

	 $sql = "SELECT * FROM posts WHERE id='$id' ORDER BY id DESC";
	 
 }
var_dump($sec) shows that showall is indeed set.

I also changed it to 1 = 1 just to see and it still wouldn't work.

How did i mess this up?


thanks guys
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

If $sec is set, the true statements will be run.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

Your else if is impossible to reach.

You're essentially doing this:

Code: Select all

if($i > 1)
{
    // Do something
}
else if ($i > 2)
{
    // If $i isn't bigger than 1, it's not bigger than 2
    // and if it is bigger than 1, it'll never get here
}
miro_igov
Forum Contributor
Posts: 485
Joined: Fri Mar 31, 2006 5:06 am
Location: Bulgaria

Post by miro_igov »

I never seen elseif not working correctly :)
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

miro_igov wrote:I never seen elseif not working correctly :)
It is working correctly, your logic is flawed and your indentation is off. Your query is also open to injection as well.

Code: Select all

if(isset($sec))
{
    if ($sec == 'showall')
    {
        $sql = "SELECT * FROM posts WHERE id='$id' ORDER BY id DESC";
    } else {
        $sql = "SELECT * FROM posts WHERE id='$id' AND section='$sec' ORDER BY id DESC"; 
    }
} else {
    // $sec is not set
}
Post Reply