0

Just trying to make a login page in php.. Here the if code is working but else code is not working.. it is also working if code.. instead of printing message.. here is the code:

session_start();  //session starts
$con=mysql_connect('localhost','root','');// connecting to ..........
mysql_select_db('news_db'); //connectin to db
if(isset($_POST['login'])) //if button login is pressed
{
    $name=$_REQUEST['username'];//getting name
    $password=$_REQUEST['password'];   //getting password
    $qyer=mysql_query("select * from news_tb where username='$name' and password='$password'"); //selecting fields
    $row=mysql_fetch_array($qyer); //fetching values in row
    if($row['username']==$name && $row['password']==$password)// condition to match the fields with database
    {   

        header("location:news1.php");  // on else also this page is opening
    }
    else
    {
        echo "pls enter valid information";    //redirects to if condition and doesnt print the msg
    }
}
Kermit
  • 33,827
  • 13
  • 85
  • 121
user2282822
  • 1
  • 1
  • 1
  • 7
    [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained [and are officially deprecated](http://j.mp/XqV7Lp). See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. – Kermit Apr 15 '13 at 15:19
  • 2
    What works and what doesnt work?? – Naftali Apr 15 '13 at 15:19
  • Indent your code. It makes it easier to spot mistakes in blocks of code. – Sverri M. Olsen Apr 15 '13 at 15:20
  • Anyway, with that kind of problem, the reason is never "else doesn't do what it is supposed to do" , but "else is actually never hit". Try to find why your if condition is always true... – Laurent S. Apr 15 '13 at 15:21
  • If you're new to this, I'd suggest looking into a good ORM (object relational mapping) library, like RedBeanPHP (redbeanphp.com). – Keshav Saharia Apr 15 '13 at 15:21
  • Unrelated, you should store your passwords encrypted. See http://stackoverflow.com/questions/10329999/php-encrypting-passwords – karmafunk Apr 15 '13 at 15:23
  • This can easily be solved by just looking at the `$_REQUEST` and `$row` variables. Those are the variables used in the `if` statement. Use the `var_dump` function to see what is in the variables. – Sverri M. Olsen Apr 15 '13 at 15:35

1 Answers1

0

Its because by pressing send or whatever, you post the code to the script. All you are doing is checking if it has been posted, not if the variables themselves are empty. Then if you have an empty row in mySQL, you will never use the else.

jacobsax
  • 37
  • 1
  • 7