我正在尝试确保在向数据库输入记录时无法重复用户名。我收到此错误“mysql_num_rows()期望参数1为资源,在C:\ xampp \ htdocs \ Syokimaufc \中给出布尔值register.php“我的用户ID字段已被自动包含,这似乎是个问题。我该如何解决这个问题?
<?php
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$email = mysql_real_escape_string($_POST['email']);
$tel = mysql_real_escape_string($_POST['tel']);
$address = mysql_real_escape_string($_POST['address']);
$checkusername = mysql_query("SELECT * FROM membership WHERE Username = '".$username."'");
if(mysql_num_rows($checkusername) == 1)
{
echo "<h1>Error</h1>";
echo "<p>Sorry, that username is taken. Please go back and try again.</p>";
}
else
{
$registerquery
= mysql_query("INSERT INTO membership (username, password, email, tel, address)
VALUES('".$username."', '".$password."', '".$email."','".$tel."','".$address."')");
if($registerquery)
{
echo "<h1>Success</h1>";
echo "<p>Your account was successfully created. Please <a href=\"index.php\">click here to login</a>.</p>";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your registration failed. Please go back and try again.</p>";
}
}
}
else
{
?>
答案 0 :(得分:1)
要避免重复的用户名,只需在数据库的用户名列中创建unique index即可。然后,如果您尝试插入重复的用户名,插入查询将失败,您可以对失败做出反应。在插入新用户名之前,无需在数据库中查找用户名。
如果不使用mysql_*
个功能,请改用PDO。并将PDO::ATTR_ERRMODE
设置为PDO::ERRMODE_EXCEPTION
,以便在检测到重复的用户名时获得一个很好的异常。
答案 1 :(得分:0)
在您的选择查询中,用户名应为用户名。因此,您的查询应该是SELECT * FROM membership WHERE username =&#39;&#34;。$ username。&#34;&#39;&#34;。您应该使用mysqli,因为不再支持mysql函数