If statement is not working correctly

76 views Asked by At

This is my first topic so far in this great webpage

The problem is this:

I'm scripting an UCP (PHP & MySQL based). I want it to show the user's status like score, money, etc. (Yeah, it's for a game) but when I click on the login button nothing happens it just erases the content of the requested fields.

It was working properly before I made some changes (Checking if the username exists)

Here's the code:

if (isset($_POST['login'])) 
{
    $hashedpass = hash('whirlpool', $password); 
    $query = "SELECT * FROM users WHERE Username = '$playername' AND Password = '$hashedpass'";
    $result = mysql_query($query);

    $num = mysql_num_rows($result);
    mysql_close();
    if($num != 0)
    {
        echo"Account doesn't exist!";
        header("Location: ucp.html");
    }
    else 
    {

        $name=mysql_result($result,$i,"UserName");

        $money=mysql_result($result,$i,"Money");

        $score=mysql_result($result,$i,"Score");

        $wantedlevel=mysql_result($result,$i,"WantedLevel");

        $adminlevel=mysql_result($result,$i,"AdminLevel");


        echo "<b>$name</b><br>Money: $money<br>Score: $score<br>Wanted Level: $wantedlevel<br>Admin Level: $adminlevel<br><br>";        

    }   
}
else if (isset($_POST['register'])) 
{
    header("Location: register.html");
}
else 
{
    header("Location: index.html");
}
2

There are 2 answers

0
Tom Lee On
if($num != 0)

change to:

if($num == 0)
0
Sir On

This simply won't work here nor does it make much logical sense:

$num = mysql_num_rows($result);
mysql_close();
if($num != 0)
{
    echo"Account doesn't exist!";
    header("Location: ucp.html");
}

First the logic is wrong, if $num is NOT equal to 0 then your query MUST have found at least one account. So you need to change your if statement to:

if($num == 0){ //if 0 rows were found - the account was not found thus it doesn't exist
   echo "Account doesn't exist!";
}

Notice also i did not add header("location: ucp.html");. You cannot display output + relocate the user to another page. You either do one or the other, or you will get an error/warning.

Finally check your MYSQL is not causing an error by adding a check at the end with :

$result = mysql_query($query) or die(mysql_error());

Final tip, you should avoid using mysql_* and look into mysqli_* or PDO best explained here: Why shouldn't I use mysql_* functions in PHP?