-2

这是我的代码:

    if ($username == "" || $pass == "" || $emailad==""|| $fname=="")
{  
    $msg = "Not all fields were entered"; 
}else
{
    if(uniqueUser($username,$emailad))
    {
        $msg="The username or email already exists";
    }else
    { 
        insertIntoDB($fname,$emailad,$username,$pass);
        $msg="The user has been inserted";

    }

}
    echo $msg;

这将用于将新用户插入我的数据库。但是我的问题是,如果我要向其中添加一个不存在的用户,程序会告诉我用户名已经存在,但是如果它不在数据库中,它将插入新帐户。因此,该程序在插入方面工作正常,具体取决于用户是否存在于数据库中。问题是我的消息显示,因为我永远不会知道用户是否已经在数据库中,因为无论我如何重写这段代码,不存在的用户插入都会导致显示错误的消息。这是因为代码将运行 if 语句,插入新用户......并再次运行显示它已经存在的消息。谁能解释为什么会这样?

独特的用户功能:

function uniqueUser($usern,$eml)
{
$query = "SELECT S.username,S.email FROM tbl_user S WHERE S.username='$usern' OR        S.email='$eml'";
return mysql_num_rows(queryMysql($query));
}
4

3 回答 3

1

大概您想回显该消息?在语句中添加echo之前。$msgif

if(uniqueUser($username,$emailad))
{
    echo $msg="The username or email already exists";
}else
{ 
    insertIntoDB($fname,$emailad,$username,$pass);
    $msg="The user has been inserted";
    echo $msg;
}

如果用户存在,则输出“用户名或电子邮件已存在”消息。如果用户不存在,那么它将被插入并输出“用户已被插入”消息。

于 2012-04-12T13:16:32.903 回答
1

尝试这个

if ($username == "" || $pass == "" || $emailad==""|| $fname=="")
{  
    $msg = "Not all fields were entered"; 
}
else if(uniqueUser($username,$emailad))
{
    $msg="The username or email already exists";
}
else
{ 
    insertIntoDB($fname,$emailad,$username,$pass);
    $msg="The user has been inserted";
}
echo $msg;
于 2012-04-12T13:27:44.270 回答
0

这是我可以建议的算法:

  1. 检查字段是否为空
  2. 检查用户是否已存在于数据库中(在这种情况下,您需要选择特定字段的基础,例如电子邮件字段或用户名字段。
  3. 成功,如果用户不存在,则将数据插入数据库。

所以这里是代码:

    <?php

/**
 * @author MESMERiZE
 * @copyright 2012
 */

if (empty($username) || empty($pass) || empty($pass) || empty($fname))
{  
        $msg = "Not all fields were entered"; 
}else
{
    // FALSE if exists TRUE if doesnt exist
    if(uniqueUser($username,$emailad) == FALSE)
    {
        $msg="The username or email already exists";

    }else
    { 
        insertIntoDB($fname,$emailad,$username,$pass);
        $msg="The user has been inserted";
        echo $msg;
    }

}

?>

将您的 uniqueUser 函数编辑为:

function userExists($usern, $eml)
{
    $query = 'SELECT * FROM tbl_user S WHERE S.username="' . $usern .
        '" OR S.email="' . $eml . '"';
    $q = mysql_query($query);
    if (mysql_num_rows($q) > 0) {
        return false;
    } else {
        return true;
    }
}
于 2012-04-12T13:23:36.983 回答