开发者

PHP mysql_num_rows() Returns error

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]


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)  . "';";


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


 $username = mysql_real_escape_string($username);

i think you have to replace the above to

$username = mysql_real_escape_string($_POST[$username]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜