-1

Hello I am currently having problem with this code i am unsure where to put my else. The error is this:

    mysql_num_rows() expects parameter 1 to be resource, boolean given in

And this is my code:

    if ($_POST['submit'])
{           

            $username = $_POST['id'];
            $password = $_POST['pass'];
            //connect to the database here
            $username = mysql_real_escape_string($username);
            $query = "SELECT hashpass, salt
                    FROM users
                    WHERE username = '$username'";
            $result = mysql_query($query);
            if(mysql_num_rows($result) < 1) //no such user exists
            {
                echo "NO USER!";
            }
            $userData = mysql_fetch_array($result, MYSQL_ASSOC);
            $hash = sha1 ( $userData['salt'] . $password );
            if($hash != $userData['password']) //incorrect password
            {
                echo "WRONG PASS";
            }
            }   

Would appreciate any help.

Anton
  • 331
  • 3
  • 16

2 Answers2

0

The mysql_num_rows function returns the number of rows in a recordset.

int mysql_num_rows ( resource $result )

The mysql_query function executes a query on a MySQL database. This function returns the query handle for SELECT queries, TRUE/FALSE for other queries, or FALSE on failure.

So in your case,you should do it like this

<?php

$link = mysql_connect("localhost", "mysql_user", "mysql_password");

$query = "SELECT hashpass, salt
                    FROM users
                    WHERE username = '$username'";

$result = mysql_query($query);

mysql_select_db("database", $link);

$result = mysql_query($query, $link);
$num_rows = mysql_num_rows($result);

if($num_rows < 1) //no such user exists
{
     echo "NO USER!";
}

?>
John Woo
  • 249,283
  • 65
  • 481
  • 481
0

In my similar script, I check $result first to ensure the query was ok... I also assume only one line per user!

$result = mysql_query($query);

if ($result)
{
  if(mysql_num_rows($result) == 1)
  {
    // user exists... check password
  }
  else
  {
    //no such user exists
    echo "NO USER!";
  }
}
else
{
  // Query failed - no such user
}

Also, just in case the snippet is applicable to your code, I'd include the password check only once you've validated the username!

Andrew
  • 1,781
  • 1
  • 21
  • 33