PHP mysql_num_rows() 返回错误
我有一个 PHP 登录脚本。这是人们可以创建新用户的部分。我的问题是我想检查用户是否存在,如果用户名在表中不存在,则创建新用户。但是,如果用户确实存在,我希望它在会话变量中返回错误。这是我现在的代码。这不包括我的数据库连接,但我知道它们确实有效。它的 num_rows()
被作为错误写入 error_log 文件中。这是代码:
$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');
它给我的错误是
mysql_num_rows(): supplied argument is not a valid MySQL result resource in [dirctory name]
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]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
mysql_num_rows()
您可以执行 SELECT COUNT(*),然后通过获取字段(应该是0 或 1)。 SELECT COUNT 将始终返回结果(当然前提是查询语法正确)。
另外,将查询:更改
为
mysql_num_rows()
Instead of doing
SELECT *
and then mysql_num_rows(), you can do aSELECT 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:
into
只是出于好奇,您听说过 upsert 吗? IE,“插入重复键”。在这种情况下,它们对您很有用,至少如果您的用户名列是唯一键的话。
http://dev.mysql.com/doc/refman /5.0/en/insert-on-duplicate.html
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
我认为你必须将上面的内容替换为
i think you have to replace the above to