Gayan Fernando
Gayan Fernando

Reputation: 57

else part doesn't work in php script

In the following php script when correct un and pass were given, it displays Welcome.But when we give wrong pass as shown in the code, it doesn't output "Wrong username password combination".what is the reason for that?

<?php
$query = mysql_query($sql);
if (!$query)
{
    echo 'Invalid query: ' . mysql_error() . "\n";
    die($message);
}
if (mysql_fetch_assoc($query))
{
    $query = mysql_query($sql);
    $row   = mysql_fetch_assoc($query);
    if ($row['un'] == $un && $row['pd'] == $encpass)
    {
        echo "<h1>WellCome</h1>";
        echo '<br /><a href="home.php?' . SID . '">page 2</a>';
        echo $row['un'];
    }
    else
    {
        echo "Wrong user name password combination";
    }
}
?>

Upvotes: 0

Views: 372

Answers (2)

Peter Krauss
Peter Krauss

Reputation: 13930

try

...
if(mysql_fetch_assoc($query)) {
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
if($row['un'] == $un && $row['pd'] == $encpass) {
    echo "<h1>WellCome</h1>";
    echo '<br /><a href="home.php?' . SID . '">page 2</a>';
    echo $row['un'];
} else
    echo "Wrong user name password combination";
} else
echo "Wrong user name password combination";
...

Upvotes: 2

luk2302
luk2302

Reputation: 57124

$Since you check for the right password in the select there will not be any row to fetch if the password is wrong, therefore you will not enter the code after mysql_fetch_assoc.

Try

if($row = mysql_fetch_assoc($query)) {
  echo "<h1>WellCome</h1>";
  echo '<br /><a href="home.php?' . SID . '">page 2</a>';
  echo $row['un'];
} else {
  echo "Wrong user name password combination";
}

Upvotes: 2

Related Questions