-1

please help me fix this code im trying to do with incorrect username or password will display if i put wrong data... this code can display if i put correct data.

it will display

Success!

but if i put wrong nothing happens.

<?php

if (isset($_POST["submit"])):

    $user = $_POST['user'];
    $pass = $_POST['pass'];

    $con = mysql_connect('localhost', 'root', '');
    mysql_select_db('login') or die ("cannot select DB");

    $query = mysql_query("SELECT * FROM userdata WHERE  username='" . $user . "' AND password='" . $pass . "'");
    $numrows = mysql_num_rows($query);

    if ($numrows != 0) {
        while ($row = mysql_fetch_assoc($query)) {
            $dbusername = $row['username'];
            $dbpassword = $row['password'];
        }

        if ($user == $dbusername && $pass == $dbpassword) {
            echo '<b>Success!</b>';
        } else {
            echo ' incorrect Username or Password ';
        }

    }

endif;

?>
MD-Tech
  • 1,224
  • 1
  • 9
  • 15
  • 2
    What if I used this as my password: `test" OR "a"="a`? It would accept it no matter which username is used. In other words: Your script is wide open to SQL injection! Please update it `MySQLi()` or `PDO()` and use Prepared Statements. – icecub Jul 28 '15 at 11:45

2 Answers2

1

You can do in few lines.

 $query = mysql_query("SELECT userId FROM userdata WHERE  username='".$user."' AND password='".$pass."'");


//$numrows=mysql_num_rows($query);
if(mysql_num_rows($query) == 1)
{
  echo "success";
}
else
  echo "Error";

If username & password not match query will return 0 rows.

See this article:How can I prevent SQL injection in PHP?

Community
  • 1
  • 1
Prashant Srivastav
  • 1,723
  • 17
  • 28
0

This is because you have written the condition inside if($numrows!=0){ .... }

One more thing, You will always have one row returned by select query as the username should be unique for each user. So, No need of while loop there.

You were not getting anything when wrong input is entered because, the select query was not returning anything. Hence, entire if($numrows!=0) {...} was skipped.

    <?php
    if(isset($_POST["submit"])):

         $user=$_POST['user'];
         $pass=$_POST['pass'];

         $con=mysql_connect('localhost', 'root', '');
         mysql_select_db('login') or die ("cannot select DB");

         $query=mysql_query("SELECT username, password FROM userdata WHERE  username='".$user."' AND password='".$pass."'");
         $numrows=mysql_num_rows($query);

        if($numrows!=0)
        {
         $dbusername=$row['username'];
         $dbpassword=$row['password'];
        }

        if($user == $dbusername && $pass == $dbpassword)
        {
            echo'<b>Success!</b>';
        }
        else 
        {
           echo' incorrect Username or Password ';
        }
    endif;

    ?>