0

I have a PHP login script. This is the part where the person can create a new user. My issue is I want to check if the user exists, and if the username does not exist the the table, than create the new user. However, if the user does exist, I want it to return an error in a session variable. Here is the code I have right now. This doesn't include my DB connections, but I know they do work. Its num_rows() that is being written as an error in the error_log file. Here is the code:

$username = mysql_real_escape_string($username);
$query = "SELECT * FROM users WHERE username = '$username';";
$result = mysql_query($query,$conn);
if(mysql_num_rows($result)>0) //user exists
{
    header('Location: index.php');
    $_SESSION['reg_error']='User already exists';
    die();
}
else
{
$query = "INSERT INTO users ( username, password, salt )
        VALUES ( '$username' , '$hash' , '$salt' );";
mysql_query($query);
mysql_close();
header('Location: index.php');

The error it is giving me is

mysql_num_rows(): supplied argument is not a valid MySQL result resource in [dirctory name]
eykanal
  • 26,437
  • 19
  • 82
  • 113
comu
  • 921
  • 1
  • 11
  • 29

3 Answers3

1

mysql_num_rows()

Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().

Instead of doing SELECT * and then mysql_num_rows(), you can do a SELECT COUNT(*) and then retrieve the number of rows, by fetching the field (that should be 0 or 1). SELECT COUNT will always return a result (provided that the query syntax is correct of course).

Also, change the query:

$query = "SELECT * FROM users WHERE username = '$username';";

into

$query = "SELECT * FROM users WHERE username = '" 
    . mysql_real_escape_string($username)  . "';";
stivlo
  • 83,644
  • 31
  • 142
  • 199
  • `SELECT 1 ... LIMIT 1` would be quicker, no? No need to count the number of users, just need to know that one exists. – mpen Oct 12 '11 at 03:31
0

Just out of curiosity, have you ever heard of upserts? I.E., "insert on duplicate key". They'd be useful to you in this situation, at least if your username column is a unique key.

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Joseph
  • 207
  • 3
  • 10
  • Never heard of it. Ill take a look – comu Oct 12 '11 at 03:00
  • I don't think he wants to perform an update "on duplicate" though... I think `INSERT IGNORE` would be better suited for the task, no? – mpen Oct 12 '11 at 03:33
0
 $username = mysql_real_escape_string($username);

i think you have to replace the above to

$username = mysql_real_escape_string($_POST[$username]);
phpuser
  • 31
  • 4